UNPKG

1.71 kBTypeScriptView Raw
1import { Expression } from "../params";
2/**
3 * A type that splits literal string S with delimiter D.
4 *
5 * For example Split<"a/b/c", "/"> is ['a' | "b" | "c"]
6 */
7export type Split<S extends string, D extends string> = string extends S ? string[] : S extends "" ? [] : S extends `${D}${infer Tail}` ? [...Split<Tail, D>] : S extends `${infer Head}${D}${infer Tail}` ? string extends Head ? [...Split<Tail, D>] : [Head, ...Split<Tail, D>] : [
8 S
9];
10/**
11 * A type that ensure that type S is not null or undefined.
12 */
13export type NullSafe<S extends null | undefined | string> = S extends null ? never : S extends undefined ? never : S extends string ? S : never;
14/**
15 * A type that extracts parameter name enclosed in bracket as string.
16 * Ignore wildcard matches
17 *
18 * For example, Extract<"{uid}"> is "uid".
19 * For example, Extract<"{uid=*}"> is "uid".
20 * For example, Extract<"{uid=**}"> is "uid".
21 */
22export type Extract<Part extends string> = Part extends `{${infer Param}=**}` ? Param : Part extends `{${infer Param}=*}` ? Param : Part extends `{${infer Param}}` ? Param : never;
23/**
24 * A type that maps all parameter capture gropus into keys of a record.
25 * For example, ParamsOf<"users/{uid}"> is { uid: string }
26 * ParamsOf<"users/{uid}/logs/{log}"> is { uid: string; log: string }
27 * ParamsOf<"some/static/data"> is {}
28 *
29 * For flexibility reasons, ParamsOf<string> is Record<string, string>
30 */
31export type ParamsOf<PathPattern extends string | Expression<string>> = PathPattern extends Expression<string> ? Record<string, string> : string extends PathPattern ? Record<string, string> : {
32 [Key in Extract<Split<NullSafe<Exclude<PathPattern, Expression<string>>>, "/">[number]>]: string;
33};