This repository has been archived by the owner on Nov 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.d.ts
63 lines (55 loc) · 1.82 KB
/
index.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
type Simplify<T> = {} & { [K in keyof T]: T[K] }
/** Extract param types from a route path literal. */
export type InferParams<
P extends string,
Value = string
> = InferParamFromPath<P> extends ParamNames<infer Required, infer Optional>
? Required | Optional extends never
? Record<string, never>
: Simplify<{ [K in Required]: Value } & { [K in Optional]?: Value }>
: never
/** Convert a route path literal to a template type. */
export type PathTemplate<P extends string> = P extends any
? P extends `${infer A}/${infer B}`
? PathTemplatePart<A, PathTemplate<B>>
: PathTemplatePart<P>
: never
type InferParamFromPath<P extends string> = P extends `${infer A}/${infer B}`
? InferParam<A, InferParamFromPath<B>>
: P extends `${infer A}&${infer B}`
? InferParam<A, InferParamFromPath<B>>
: InferParam<P, { required: never; optional: never }>
type InferParam<
T extends string,
Acc extends ParamNames
> = T extends `:${infer P}${'?' | '*'}`
? AddOptionalParam<Acc, P>
: T extends `:${infer P}${'+' | ''}`
? AddRequiredParam<Acc, P>
: Acc
type AddOptionalParam<PG extends ParamNames, P extends string> = ParamNames<
PG['required'],
PG['optional'] | P
>
type AddRequiredParam<PG extends ParamNames, P extends string> = ParamNames<
PG['required'] | P,
PG['optional']
>
interface ParamNames<R extends string = string, O extends string = string> {
required: R
optional: O
}
type PathTemplatePart<
Part extends string,
Rest extends string = never
> = Part extends `:${string}${'?' | '*'}`
? Rest | PathConcat<string, Rest>
: Part extends `:${string}${'+' | ''}`
? PathConcat<string, Rest>
: PathConcat<Part, Rest>
type PathConcat<Left extends string, Right extends string> = unknown &
([Left] extends [never]
? Right
: [Right] extends [never]
? Left
: `${Left}/${Right}`)