Skip to content

Instantly share code, notes, and snippets.

@tecsoc
Last active October 7, 2023 00:46
Show Gist options
  • Save tecsoc/cfa7688b0cc514ded50595dc85f18dc1 to your computer and use it in GitHub Desktop.
Save tecsoc/cfa7688b0cc514ded50595dc85f18dc1 to your computer and use it in GitHub Desktop.
type StringKeyToAnyValue = Record<string, any>;
// 「.」より前の文字列を取り出す型
type HeadProperty<T extends string> = T extends `${infer First}.${string}` ? First : T;
// 「.」より後の文字列を取り出す型
type TailProperty<T extends string> = T extends `${string}.${infer Rest}` ? Rest : never;
// ネストしているオブジェクトを再起的にPickする型
type DeepPick<T extends StringKeyToAnyValue, U extends string> = {
[K in HeadProperty<U> & keyof T]: K extends readonly unknown[] // Union Typesかどうか
? DeepPick<T[K][number], TailProperty<U>>
: T[K] extends StringKeyToAnyValue
// T[K]がオブジェクトである場合に再帰する
? DeepPick<T[K], TailProperty<U>>
: T[K];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment