Skip to content

Instantly share code, notes, and snippets.

@ferdaber
Last active February 12, 2019 21:10
Show Gist options
  • Save ferdaber/e32d1fa719947138c00be01f4e3a7678 to your computer and use it in GitHub Desktop.
Save ferdaber/e32d1fa719947138c00be01f4e3a7678 to your computer and use it in GitHub Desktop.
route-props.tsx
import { RouteComponentProps } from '@reach/router'
import {
ComponentType,
ComponentClass,
FunctionComponent,
JSXElementConstructor,
ComponentProps,
} from 'react'
// method 1
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
export type RouteProps = Required<RouteComponentProps>
export type OuterRouteProps =
| {
path: string
default?: boolean
}
| {
path?: string
default: string
}
type EnhanceProps<TPathParams, TProps extends RouteProps & TPathParams> = Omit<
TProps,
keyof RouteComponentProps | keyof TPathParams
> &
OuterRouteProps
declare function TestRoute(props: RouteProps & JSX.IntrinsicElements['a']): JSX.Element
// reach-router automatically injects route props like 'path', 'default', 'location', 'navigate', etc...
// to any children of <Router />, and also adds a required path or default external prop for that component
// acting as a route. It also injects any path params that are parsed successfully
export function asRoute<
TPathParams = {},
TProps extends RouteProps & TPathParams = RouteProps & TPathParams
>(Component: FunctionComponent<TProps>): FunctionComponent<EnhanceProps<TPathParams, TProps>>
export function asRoute<
TPathParams = {},
TProps extends RouteProps & TPathParams = RouteProps & TPathParams
>(Component: ComponentClass<TProps>): ComponentClass<EnhanceProps<TPathParams, TProps>>
export function asRoute<TProps extends RouteProps>(Component: ComponentType<TProps>) {
// hoc doesn't actually do anything, it's just a helper to inject route props and add path or default as required params
return Component as any
}
const TestRouteAsRoute = asRoute(TestRoute)
// method 2
type GenericRouteProps<C extends JSXElementConstructor<RouteProps>> = {
as: C
} & Omit<JSX.LibraryManagedAttributes<C, ComponentProps<C>>, keyof RouteComponentProps> &
OuterRouteProps
export declare function Route<C extends JSXElementConstructor<any>>(
props: GenericRouteProps<C>
): JSX.Element
const TestRouteAsRoute2 = <Route as={TestRoute} path="" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment