Skip to content

Instantly share code, notes, and snippets.

@natemoo-re
Last active November 4, 2020 19:30
Show Gist options
  • Save natemoo-re/e1fc5f4af634ee7e5d64aa0fb0ea6fb5 to your computer and use it in GitHub Desktop.
Save natemoo-re/e1fc5f4af634ee7e5d64aa0fb0ea6fb5 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