type NameOrId<T extendsnumber|string>=T extendsnumber?IdLabel:NameLabel; functioncreateLabel<Textendsnumber|string>(idOrName:T):NameOrId<T>{ throw"unimplemented"; } let a=createLabel("typescript"); //let a:NameLabel let b=createLabel(2.8); //let b:IdLabel let c=createLabel(Math.radom()?"hello":42); //let c:NameLabel|IdLabel
条件类型约束
1 2 3 4 5 6 7 8 9 10 11
type MessageOf<T extends {message:unknown} ? T["message"]:never; interface Email { message:string; } interface Dog { bark():void; } type EmailMessageContents=MessageOf<Email>; //type EmailMessageContents=string type DogMessageContents=MessageOf<Dog>; //type DogMessageContents=nerver
在条件类型里推断
infer关键词,可以从正在比较的类型中推断类型,然后在true分支里引用该推断结果
1 2 3 4 5 6 7
type Flatten<T>=T extendsany[]?T[number]:T;//number索引用来获取数组元素的类型 type Str=Flatten<string[]>; //type Str=string type Num=Flatten<number>; //type Num=number; //用infer type Flatten<Type>=Type extendsArray<infer Item>?Item:Type
使用infer写一些有用的类型帮助别名,我们可以获取一个函数返回的类型:
1 2 3 4 5
type GetReturnType<Type>=Type extends (...args:nerver[])=>infer Return ?Return :never; type Num=GetReturnType<()=>number>; //type Num=number; type Str=GetReturnType<(x:string)=>string>; //type Str=string