Skip to content

Instantly share code, notes, and snippets.

@asvny
Forked from natemoo-re/RouteParams.ts
Created November 4, 2020 19:30
Show Gist options
  • Save asvny/e2bb0f14bc8bcb0ef581fbd2e73862e3 to your computer and use it in GitHub Desktop.
Save asvny/e2bb0f14bc8bcb0ef581fbd2e73862e3 to your computer and use it in GitHub Desktop.
Typed parameter object from path
type RestParam<S extends string> = S extends `...${infer A}` ? A : never;
type StandardParam<S extends string> = S extends `...${infer A}` ? never : S;
type ExtractParams<S extends string> = S extends `[${infer A}]` ? A : never;
type TupleToUnion<T extends any[]> = T[number];
type Split<S extends string> =
string extends S ? string[] :
S extends '' ? [] :
S extends `${infer T}/${infer U}` ? [T, ...Split<U>] :
[S];
type NormalizePath<S extends string> = S extends `/${infer T}` ? T : S;
type AllPathParams<S extends string, P extends string = ExtractParams<TupleToUnion<Split<NormalizePath<S>>>>> = { [param in P]: string|string[] };
type RestParams<S extends string, Base extends string = keyof AllPathParams<S>> = { [a in RestParam<Base>]: string[] };
type StandardParams<S extends string, Base extends string = keyof AllPathParams<S>> = { [a in StandardParam<Base>]: string };
export type PathParams<S extends string> = RestParams<S> & StandardParams<S>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment