infer 예약어 with Conditional Type
타입스크립트의 타입 추론 기능을 극한까지 활용하는 기능
Copy // 배열이 있을 때 배열의 요소 타입을 얻어내고 싶은 상황
type El < T > = T extends ( infer E )[] ? E : never ;
type Str = El < string []>; // string
type NumOrBool = El <( number | boolean )[]>; // number | boolean
Copy type MyParameters < T > = T extends ( ... args : infer P ) => any ? P : never ;
type MyConstructorParam < T > = T extends abstract new ( ... args : infer P ) => any ? P : never
type MyReturnType < T > = T extends ( ... args : any ) => infer R ? R : any
type MyInstanceType < T > = T extends abstract new ( ... args : any ) => infer R ? R : any
type P = MyParameters <(a : string , b : number ) => string > // [a: string, b: number]
type R = MyReturnType <(a : string , b : number ) => string > // string
type CP = MyConstructorParam < new (a : string , b : number ) => {}> // [a: string, b: number]
type I = MyInstanceType < new (a : string , b : number ) => {}> // {}
Copy type MyPAndR < T > = T extends ( ... args : infer P ) => infer R ? [ P , R ] : never ;
type PR = MyPAndR <(a : string , b : number ) => string >; //[[a: number, b: string], string]
Copy type Union < T > = T extends { a : infer U , b : infer U } ? U : never ;
type Result1 = Union <{ a : 1 | 2 , b : 2 | 3 }>; // 1 | 2 | 3
type Intersection < T > = T extends {
a : (pa : infer U ) => void ,
b : (pb : infer U ) => void ,
} ? U : never ;
type Result2 = Intersection <{ a (pa : 1 | 2 ) : void , b (pb : 2 | 3 ) : void }>; // 2
매개변수에 같은 타입 변수를 선언하면 인터섹션이 된다.
Copy type UnionToIntersection < U >
= ( U extends any ? (p : U ) => void : never ) extends (p : infer I ) => void
? I
: never
type Result = UnionToIntersection <{ a : number } | { b : string }>; //{a:number} & {b:string}
type Result2 = UnionToIntersection < boolean | true >; // never;