UNPKG

ts-deep-pick

Version:

TypeScript utility generating new types by deep picking/omitting, leveraging Template Literal Types from TypeScript >= 4.1

29 lines 2.49 kB
import { Identical, Primitive, UnionKeyOf } from "ts-typetools"; import { DeepPickGrammar, DefaultGrammar } from "./DeepPickGrammar"; import { DeepPickPath } from "./DeepPickPath"; import { Opaque } from "./Opaque"; export declare type DeepPick<T, K extends DeepPickPath<T, G>, G extends DeepPickGrammar = DefaultGrammar> = T extends Opaque ? T : T extends Primitive ? T : T extends Array<infer Item> ? DeepPick<Item, ArrayItemKey<K, G>, G>[] : [K] extends [G["glob"]] ? T : Rename<ShouldPick<K, G> extends true ? Pick<InnerPick<T, K, G>, PickOuterKey<K, G> & UnionKeyOf<T>> : ShouldOmit<K, G> extends true ? Omit<InnerPick<T, K, G>, OmitOuterKey<K, G>> : InnerPick<T, K, G>, T>; declare type ArrayItemKey<K extends string, G extends DeepPickGrammar> = InnerKey<G["array"], K, G>; declare type InnerPick<T, K extends DeepPickPath<T, G>, G extends DeepPickGrammar> = { [key in keyof T]: DeepPick<T[key], InnerKey<key & string, K, G>, G>; }; declare type InnerKey<key extends string, K, G extends DeepPickGrammar> = [ Extract<K, `${Empty | G["mutate"]}${key}${G["prop"]}${string}`> ] extends [`${Empty | G["mutate"]}${key}${G["prop"]}${infer K}`] ? K : never; declare type ShouldPick<K extends string, G extends DeepPickGrammar> = [ ExcludeMutateKey<ExcludeOmitKey<K, G>, G> ] extends [G["glob"]] | [never] ? false : true; declare type ShouldOmit<K extends string, G extends DeepPickGrammar> = [ Extract<K, `${G["mutate"]}${string}`> ] extends [string] ? true : false; declare type PickOuterKey<K extends string, G extends DeepPickGrammar> = Exclude<StripMutateKey<ExcludeOmitKey<KeyHead<K, G>, G>, G>, OmitOuterKey<K, G>>; declare type OmitOuterKey<K extends string, G extends DeepPickGrammar> = ExtractOmitKey<KeyHead<K, G>, G>; declare type ExcludeOmitKey<K extends string, G extends DeepPickGrammar> = Exclude<K, `${G["omit"]}${string}`>; declare type ExtractOmitKey<K extends string, G extends DeepPickGrammar> = K extends `${G["omit"]}${infer K}` ? K : never; declare type ExcludeMutateKey<K extends string, G extends DeepPickGrammar> = Exclude<K, `${G["mutate"]}${string}`>; declare type StripMutateKey<K extends string, G extends DeepPickGrammar> = K extends `${G["mutate"]}${infer K}` ? K : K; declare type KeyHead<K extends string, G extends DeepPickGrammar> = K extends `${infer K}${G["prop"]}${string}` ? K : K; declare type Empty = ""; declare type Rename<T, Alias> = Identical<T, Alias> extends true ? Alias : T; export {}; //# sourceMappingURL=DeepPick.d.ts.map