学习TypeScript26(TS进阶用法infer )

222 阅读1分钟

infer 是TypeScript 新增到的关键字 充当占位符

我们来实现一个条件类型推断的例子

定义一个类型 如果是数组类型 就返回 数组元素的类型 否则 就传入什么类型 就返回什么类型

type Infer<T> = T extends Array<any> ? T[number] : T
 
 
type A = Infer<(boolean | string)[]>
 
type B = Infer<null>

使用inter 修改

type Infer<T> = T extends Array<infer U> ? U : T
 
 
type A = Infer<(string | Symbol)[]>

例子2配合tuple 转换 union 联合类型

type TupleToUni<T> = T extends Array<infer E> ? E : never
 
type TTuple = [string, number];
 
type ToUnion = TupleToUni<TTuple>; // string | number

转载自:blog.csdn.net/qq119556631…

作者:小满