DEV Community

Discussion on: Type-Safe Usage of React Router

Collapse
 
sirmoustache profile image
SirMoustache

You can extract types from path with TypeScript template literal types
like:

type ExtractRouteParams<T> = string extends T
    ? Record<string, string>
    : T extends `${infer _Start}:${infer Param}/${infer Rest}`
    ? { [k in Param | keyof ExtractRouteParams<Rest>]: string }
    : T extends `${infer _Start}:${infer Param}`
    ? { [k in Param]: string }
    : {};

type Params = ExtractRouteParams<'/post/:id'>; // // type is {id: string}
type Params = ExtractRouteParams<'/calendar/:year/:month'>; // type is {year: string; month: string}
Enter fullscreen mode Exit fullscreen mode

Can read more about this here and here

Collapse
 
0916dhkim profile image
Danny Kim

Thank you for sharing this feature! It is shocking how this is possible in TS. I am so excited to update my example!

Collapse
 
0916dhkim profile image
Danny Kim

The post & examples are updated, and many duplicates are removed. Your suggestion helped a lot.