
TypeScript の高度な型 ⑩ 独自定義 Utility Types
TypeScript の高度な型 ⑩ 独自定義 Utility Types
TypeScript 2.8 で導入された Conditional Types や、 TypesScript 3.0 で導入された Tuple Spread により、
既存型から様々な型を抽出したり、加工したりすることが可能です。
Unbox 型
オブジェクトの子ノードをUnion Types で取得する型です。
type Unbox<T> = T extends {[K in keyof T]: infer U} ? U : never
type T = Unbox<{a: 'a' b: 'B'; c: 'C'}>
型推論結果
type T = 'A' | 'B' | 'C'
UnionToIntersection型
Union TypeをIntersection Typesに変換する型です。
type UTI<T> = T extends any ? (args: T) => void : never
type UnionToInteresection<T> = UTI<T> extends <args: infer I) => void ? I : never
利用例
type A_or_B = {a: "a"} | {b: "b"}
type A_and_B = UnionToInteresection<A_or_B>
// type A_and_B = {a: "a"} & {b: "b"}
NonEmptyList型
Genericsに指定した型に該当する要素を最低でも一つ含む必要がある型です。
type NonEmptyList<T> = [t, ...T[]]
使用例
const list1: NonEmptyList<string> = [] // Error
const list2: NonEmptyList<string> = ['test'] // No Error
PickSet型
Setの値型を取得する型です。
type PickSet<T> = T extends Set<infer I> ? I : never
値をUnion Types で取得するためには、 const assertion を利用します。
const set = new Set([1, 2] as const)
type SetValues = PickSet<typeof set> // 1 | 2
PickMapKeys 型
Mapのキーを取得する型です。
const map = new Map([[0, 'far'], [1, 'bar']]as const)
type PickMapKeys<T> = T extends Map<infer K, any> ? K : never
type MapKeys = PickMapKey<typeof map>
利用例
type MapKeys: 0 | 1