1 interface Bird{ 2 fly:boolean; 3 sing:()=>{} 4 } 5 interface Dog{ 6 fly:boolean; 7 bark:()=>{} 8 } 9 //不会提示sing和bark方法需要判断,直接使用会报错 10 //两种常用方法:一种用 as 一种用 in 11 function trainAnial(animal:Bird|Dog){ 12 if(animal.fly){ 13 (animal as Bird).sing() 14 }else{ 15 (animal as Dog).bark() 16 } 17 } 18 function fn1(animal:Bird|Dog){ 19 if('sing' in animal){ 20 animal.sing() 21 }else{ 22 animal.bark() 23 } 24 } 25 //一个为字符串就会报错 26 function add (first:number|string,secound:number|number){ 27 if(typeof first=='string'||typeof secound=='string'){ 28 return 0 29 } 30 return first+secound 31 } 32 //必须为类 33 class NumberObj{ 34 count:number 35 } 36 function addA(first:object|NumberObj,secound:object|NumberObj){ 37 if(first instanceof NumberObj&&secound instanceof NumberObj){ 38 return first.count+secound.count 39 40 } 41 return 0 42 }