//类型收窄 //typeof 类型收窄 function uppercase(content:string|number) { if(typeof content string)//收窄的类型有限 { return content.toUpperCase(); } return content; } //真值收窄 function getString(content?:string)//加表示参数可传可不传 { if(typeof content string) { if(content) { return content.toUpperCase(); } } } //相等收窄 function example(x:string | number,y:string | boolean) { if(x y) { return x.toUpperCase(); } } //对象类型结构的代码怎么写 function getObjectValue({a,b}:{a:number,b:number}) { return a b; } getObjectValue({a:1,b:2}); //变量类型以定义变量时的类型为准 let username:string | number 123;type Fish { swim:(){ } } type Bird { fly:(){ } } //In 语法下的类型收窄 function test(animal:Fish|Bird) { if(swim in animal) { return animal.swim(); } return animal.fly(); } //InstanceOf语法下的类型收窄 function test1(param:Date | string) { if(param instanceof Date) { return param.getTime(); } return param.toUpperCase(); } //animal is Fish 叫做类型陈述语法 function isFish(animal:Fish|Bird): animal is Fish { if((animal as Fish).swim ! undefined) { return true; } return false; } function test2(animal:Fish | Bird) { if(isFish(animal)) { return animal.swim(); } return animal.fly(); }