一、类型断言
两种写法 : 1. 值 as 类型 2. <类型>值
使用类型断言一定要谨慎,类型断言只能规避编译时候的错误;但是不能避免运行时候的错误
1.声明两个接口
// 猫
interface Icat{
name : string
run() :void
}
// 鱼
interface Ifish{
name : string
swim() :void
}
2。ts只允许我们访问联合数据类型的共有属性和方法;
如果不是共有的不能访问
// function isFish(animal:Icat|Ifish):boolean{
// // 类型“Icat”上不存在属性“swim” swim 这个地方会报错
// if(typeof animal.swim == 'function'){
// // 鱼
// return true
// }else{
// // 🐱
// return false
// }
// }
1、 (值 as 类型).属性/方法
// function isFish(animal:Icat|Ifish):boolean{
// if(typeof (animal as Ifish ) .swim == 'function'){
// // 鱼
// return true
// }else{
// // 🐱
// return false
// }
// }