随笔 - 24,  文章 - 0,  评论 - 1,  阅读 - 16503
复制代码
 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 }
复制代码

 

posted on   小白学前端  阅读(221)  评论(0编辑  收藏  举报

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示