interfaceBird{
fly: boolean;
sing:()=>{};}interfaceDog{
fly: boolean;
bark:()=>{};}//类型断言的方式 进行类型保护functiontrainAnmial(animal: Dog | Bird){if(animal.fly){(animal as Bird).sing();}else{(animal as Dog).bark();}}
2,in 语法来做类型保护
//in 语法来做类型保护functiontrainAnmial2(animal: Dog | Bird){if('sing'in animal){
animal.sing();}else{
animal.bark();}}
3,typeof方式 语法来做类型保护
functionadd(first: string | number, second: string | number){if(typeof first ==='string'||typeof second ==='string'){return`${first}${second}`;}return first + second;}
4,使用 instanceof 语法来做类型保护
classNumberObj{
count: number =0;}functionadd2(first: object | NumberObj, second: object | NumberObj){if(first instanceofNumberObj&& second instanceofNumberObj){return first.count + second.count;}return0;}