Skip to content

Instantly share code, notes, and snippets.

@nickserv
Last active October 20, 2022 10:14
Show Gist options
  • Save nickserv/e69700cf1a4772d9023860a895e6172b to your computer and use it in GitHub Desktop.
Save nickserv/e69700cf1a4772d9023860a895e6172b to your computer and use it in GitHub Desktop.
Type safe children with React and TypeScript https://twitter.com/nickemccurdy/status/1583036771415519232
import {
ComponentType,
createElement,
FunctionComponent,
ReactElement,
ReactNode,
} from "react"
interface RouteProps {
path?: string
element?: ReactNode
}
declare const Route: FunctionComponent<RouteProps>
declare const Routes: ComponentType<{
children?:
| ReactElement<RouteProps, typeof Route>
| ReactElement<RouteProps, typeof Route>[]
}>
declare const HomePage: ComponentType
export default function App() {
return (
<Routes>
{[
createElement(Route, { path: "/", element: <HomePage /> }),
// @ts-expect-error
createElement("p", null, "Oops! This is not a route."),
]}
</Routes>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment