背景 今回もmattさんのTypeScriptTipsを解説していく。
TypeScript Tip #20
概要 以下のオブジェクトの型が存在している時に、特定のキーのバリューのユニオンを作成する時に使用する。
export type Obj = { a: 'a', a2: 'a2', a3: 'a3', b: 'b', b1: 'b1', b2: 'b2' } // 上記の型から以下の型を作成したい type NewUnion = "a" | "a2" | "a3" 本題 以下が実際の型定義になる。順番に解説していく。
type ValuesOfKeysStartingWithA<Obj> = { [K in Extract<keyof Obj, `a${string}`>]: Obj[K]; }[Extract<keyof Obj, `a${string}`>] type NewUnion = ValuesOfKeysStartingWithA<Obj> // type NewUnion = "a" | "a2" | "a3" 今回のポイントはExtract<keyof Obj,`a${string}`>になるため細かくみていく。 まず、a${string}がどのように型定義されるかというと、文字列aを含めて文字列リテラル型を定義できる。 type TestType = `a${string}` // Success const test1: TestType = 'a' const test2: TestType = 'a1' // Error const test3: TestType = '1' // Type '"1"' is not assignable to type '`a${string}`'.