例子
type Arr = Array<string | number>;
type ArrInfer<T> = T extends Array<infer U> ? U : T;
type Res = ArrInfer<Arr>; // string | number
type ElementOf<T> = T extends Array<infer E> ? E : T;
type Tuple = string[];
type Un = ElementOf<Tuple>; // string
type Arr = (name: string, age: number) => number;
type ArrInfer<T> = T extends Array<infer U> ? U : T;
type Res = ArrInfer<Arr>; // (name: string, age: number) => number;
infer表示推断占位 infer U 联合起来就表示 这个类型我不确定未知,就暂时表示为 "U"
那上面的 类型Arr 是符合 Array<infer U>的结构规则,符合的话,就返回U,不符合返回T
- 获取函数返回值
type Func = (name: string, age: number) => number;
type GetFunc<T> = T extends (name: any, age: any) => infer U ? U : T;
type ResFunc = GetFunc<Func>; // number
- infer 推断出交叉类型
type T1 = { name: string };
type T2 = { age: number };
type K2<T> = T extends { a: (x: infer U) => void; b: (x: infer U) => void }
? U
: never;
interface Props {
a: (x: T1) => void;
b: (x: T2) => void;
}
type k3 = K2<Props>;
网友评论