Created
February 23, 2021 20:32
-
-
Save Peeja/40b043eb02287fa3e63679427cac96b6 to your computer and use it in GitHub Desktop.
Inferring the type of route params from a route path string: An exercise in what template literal types can do (https://www.typescriptlang.org/play?#code/C4TwDgpgBACghsAFgZQgcwLYQHbAM4A88SUEAHsDgCZ5R7ABOAltmgDRSqY75QC8UbBABuEBgD5+sBIlIVqtAAYASAN4sAZmM7osuAL4B6NZu0AlCPX2KoAfmlIue-AQv0OTnrQA+O7rkkALj9nHwdEAG4AKFBIaQY4DE9cQmQ5SmwaOkYWNEkBNPIMrMVAk2…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type PathSegments<Path extends string, Segments = never> = Path extends `${infer Segment}/${infer Rest}` ? PathSegments<Rest, Segments | Segment> : Segments | Path; | |
type ParamSegments<S extends string> = S extends `:${infer P}` ? P : never; | |
let segments: PathSegments<'/posts/:id/comments/:comment_id'>; | |
interface Routes { | |
match<Path extends string>(path: Path, cb: (params: Record<ParamSegments<PathSegments<Path>>, string>) => void): void; | |
} | |
declare const routes: Routes | |
routes.match('/posts/:id/comments/:comment_id', (params) => { | |
console.log({params}) | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment