function swim(animal: Cat | Fish) {
//类型断言用于解决 “不确定一个联合类型的变量到底是哪个类型的时候,我们只能访问此联合类型的所有类型中共有的属性或方法”
//需要用typeof (animal as Cat).run === 'function' 作类型确定,否则使用不当会造成运行时错误
if(typeof (animal as Cat).run === 'function'){
console.log("Cat");
(animal as Cat).run();
}else{
console.log("Fish");
(animal as Fish).swim();
}
}
const tom: Cat = {
name: 'Tom',
run() { console.log('run') }
};
swim(tom);
TS类型断言作用
最新推荐文章于 2024-05-09 11:33:33 发布