-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore(pattern): enhance types syntax/readability (#275)
- Loading branch information
Showing
1 changed file
with
23 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,35 +1,41 @@ | ||
/* eslint-disable @typescript-eslint/ban-types */ | ||
/* eslint-disable @typescript-eslint/no-unused-vars */ | ||
|
||
type Simplify<T> = {[KeyType in keyof T]: T[KeyType]} & {}; | ||
type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {}; | ||
|
||
type ConvertEmptyRecord<T, R = string> = T extends Record<string, never> ? R : T; | ||
|
||
type TupleToObject<T extends Array<string>> = { | ||
[key in ExtractPattern<T[number]>]: string | ||
}; | ||
|
||
type Split<S extends string, D extends string> = | ||
string extends S ? Array<string> : | ||
string extends S ? string[] : | ||
S extends "" ? [] : | ||
S extends `${infer T}${D}${infer U}` ? [`${T}${D}`, ...Split<U, D>] : [S]; | ||
|
||
type Trim<T> = T extends `${" "}${infer U}` ? | ||
Trim<U> : T extends `${infer U}${" "}` ? Trim<U> : T; | ||
type Trim<S extends string> = | ||
S extends ` ${infer U}` ? Trim<U> : | ||
S extends `${infer U} ` ? Trim<U> : | ||
S; | ||
|
||
type Concat<T extends Array<string>> = T extends [ | ||
infer F extends string, | ||
...infer R extends Array<string> | ||
] ? `${F} ${Concat<R>}` : ""; | ||
type Concat<T extends string[]> = T extends [infer F extends string, ...infer R extends string[]] | ||
? `${F} ${Concat<R>}` | ||
: ""; | ||
|
||
type ArrayToString<T extends LokiPatternType> = | ||
T extends Array<string> ? Concat<T> : | ||
T extends ReadonlyArray<string> ? Concat<[...T]> : T; | ||
T extends string[] ? Concat<T> : | ||
T extends readonly string[] ? Concat<[...T]> : | ||
T; | ||
|
||
type ExtractPattern<Pattern extends string> = | ||
Pattern extends `${infer _}<${infer Name}>${infer _}` ? | ||
(Name extends "_" ? never : Trim<Name>) | ||
: | ||
never; | ||
|
||
type TupleToObject<T extends string[]> = { | ||
[key in ExtractPattern<T[number]>]: string; | ||
}; | ||
|
||
type ExtractPattern<Pattern extends string> = Pattern extends `${infer _}<${infer Name}>${infer _}` ? | ||
Name extends "_" ? never : Trim<Name> : never; | ||
export type LokiPatternType = string | string[] | readonly string[]; | ||
|
||
export type LokiPatternType = string | Array<string> | ReadonlyArray<string>; | ||
export type LokiLiteralPattern<T extends LokiPatternType> = ConvertEmptyRecord<Simplify< | ||
TupleToObject<Split<ArrayToString<T>, ">">> | ||
>>; |