-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathindex.ts
51 lines (39 loc) · 1.39 KB
/
index.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
// Author: anuraghazra
// https://github.com/anuraghazra/type-trident
type ExtractGroups<T> = T extends `${string}(${infer Name})${infer Rest}`
? [Name, ...ExtractGroups<Rest>]
: [];
type ExtractName<T> = T extends `${string}?<${infer Name}>${infer Rest}`
? [Name, ...ExtractName<Rest>]
: [];
type TupleToObject<T extends string[]> = {
[K in T[number]]: string;
};
type RegExpIndexes<T extends number[]> = {
[K in T[number]]: string;
};
type Length<T extends any[]> = T["length"] & number;
type Push<T extends any[], Val> = [...T, Val];
type NTuple<N extends number, T extends any[] = []> = T["length"] extends N
? T
: NTuple<N, Push<T, T["length"]>>;
const safeExec = <R extends string>(regex: R, str: string) => {
type Names = ExtractName<R>;
type Groups = TupleToObject<Names>;
type GroupCount = ExtractGroups<R>;
type GroupLength = Length<Push<GroupCount, any>>;
type RegExpResult =
| null
| (Omit<RegExpExecArray, "length" | keyof Array<any>> & {
length: GroupLength;
groups: Groups;
} & RegExpIndexes<NTuple<GroupLength>>);
return new RegExp(regex).exec(str) as RegExpResult;
};
const regex = "First_Name: (?<firstname>w+), Last_Name: (?<lastname>w+)";
const match = safeExec(regex, "First_Name: John, Last_Name: Doe");
// has groups [0], [1], [2]
match?.[2];
// @ts-expect-error no 3rd group
match?.[3];
match?.groups.firstname; // <-- auto complete