[TypeScript] Combine Template Literal Types usage, Extract and default Generic type
阿新 • • 發佈:2022-04-22
For example we have a type like this:
type Obj = { a: "a"; a2: "a2"; a3: "a3"; b: "b"; b1: "b1"; b2: "b2"; };
We want to constrct a new type which porps starts with letter 'a':
type keyStartingWithA = { [K in Extract<keyof Obj, `a${string}`>]: Obj[K]; };
So why this works?
Extract: get shared key from 'keyof Obj' (which is "a" | "a1" | "a2" | "b" | "b1" | "b2")
`a${string}` work as wired card: 'a*', * should be type string
So if we change to:
type keyStartingWithA = { [K in Extract<keyof Obj, `a${number}`>]: Obj[K]; };
OK, now we get Obj back starting with A, if we only want values of it.
type ValuesOfKeysStartingWithA = { [K in Extract<keyof Obj, `a${string}`>]: Obj[K]; }[Extract<keyof Obj, `a${string}`>];
Then we can improve the type to make it more generic
type ValuesOfKeysStartingWithA<T> = { [K in Extract<keyof T, `a${string}`>]: T[K]; }[Extract<keyof T, `a${string}`>]; type NewUnion = ValuesOfKeysStartingWithA<Obj>
Finially, you can notice that
Extract<keyof T, `a${string}`
repeated two times, we can improve those by using default type of Generic types
type ValuesOfKeysStartingWithA< T, _ExtractedKeys extends keyof T = Extract<keyof T, `a${string}`> > = { [K in _ExtractedKeys]: T[K]; }[_ExtractedKeys];
Creates a default variable _ExtractedKeys
Assign it to
Extract<keyof T, `a${string}`>
Need to use following to keep it working
extends keyof T