T extends U ? X : Y - 如果T是U的子集,则返回X类型否则返回Y类型
type Other = 'a' | 'b';type Merge = T extends "x" ? T : Other;// 当泛型传入的是x时,则返回的是x类型,当泛型传入的是y类型时,则返回是Other类型,所以联合一起就是"x" | "a" | "b";type Values = Merge<"x" | "y">;// type Values = "x" | "a" | "b"// 联合类型里面的每一个值都要去匹配type Merge = T extends U ? nerer : T;type Values1 = Merge<"x" | "y" | "z","x">;// type Values1 = nerer Merge// type Values1 = "y" Merge// type Values1 = "z" Merge// 所以 type Values1 = 'y' | 'z'type Merge = T extends {a:string,b:number} ? T : never;// 只管传入的T里面符合{a:string,b:number}则返回T,否则返回nevertype Values1 = Merge<{a:string,b:number,c:boolean}>;// Values1 = {a:string,b:number,c:boolean};
infer - 推断extends的字句类型,infer为匹配时符合条件的类型
type Values = T extends (...args:any[]) => infer R ? R : T;// 当T是(...args:any[]) => R的返回值类型,则返回R类型,否则返回T类型type Values1 = Values<()=>number>;// type Values = number; infer推断T的返回值type Values = T extends (infer R)[] ? R : T;// R为数组元素类型 string[] R就为string number[] R为numbertype Values1 = Values;// infer推断数组类型// type Values = number;type Values = T extends {a:infer U,b:infer U} ? U : never;// infer 匹配传入的a的类型和b的类型type Values1 = Values<{a:number,b:number}>;// type Values1 = number;type Values2 = Values<{a:number,b:string}>;// type Values2 = number | string;type Values3 = Values<{a:number,b:string,c:boolean}>;// 匹配符合条件的项// type Values3 = number | string;type Values4 = Values<{c:boolean}>;// type Values4 = never;
ReturnType - 获取传入的T的返回值类型
type Values = ReturnType<()=>number>;// type Values = number;
keyof - 用于获取某种类型的所有键,其返回类型是联合类型
interface B { id: number; name: string; age: number;}type B1 = keyof B;// type B1 = "id" | "name" | "age"
Record<K,V> - V作为K的属性
type Methods = 'GET' | 'POST'type Types = Record<Methods,any>// type Types = {GET: any,POST: any}type test = { name:string, age:number}type Types = Record<string,test>// type Types = { [x:string]: {name:string,age:number}}
Partial - 属性转换为可选类型
type ITest = { name:string age:number}type Types = Partial<ITest>// type Types = {name?:string,age?:number}
Omit<I,'name'> - I里面删除name属性
type Itest = { name:string age:number}type Types=Omit<Itest,"name">// type Types = {age:number}
Required - 将T里面的属性全部转为必须属性
type Types = { name?:string age?:number}type Types1 = Required<Types>// type Types1 = {name:string,age:number}
Pick<T,属性> - 从T里面选取属性
type Types = { name:string, age:number}type Types1 = Pick<Types,'name'>// type Types1 = {name:string}
Readonly - 将T里面的属性转为readonly
type Types = { name:string, age:number}type Types1 = Readonly<Types>// type Types1 = { readonly name: string; readonly age: number;}
Exclude<T,属性> - 将T里面的属性排除,T为联合类型
type Types = 'name' | 'age' | 'address'type Types1 = Exclude<Types,'name'>// type Types1 = 'age' | 'address'
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。