interface Cat {
name: string;
run(): void;
}
interface Fish {
name: string;
swim(): void;
}
function isFish(animal: Cat | Fish) {
if (typeof (animal as Fish).swim === "function") {
return true;
}
return false;
}
function swimAsFish(animal: Cat | Fish) {
(animal as Fish).swim(); // 虽然animail断言为Fish类型,躲避检查报错,但若animail不为Fish对象,运行时还是要报错
}
function swimAsAny(animal: Cat | Fish) {
(animal as any).swim(); // 同理,animail断言为any类型,但any没有swim方法,运行时报错
}
const catObj = {
name: "cat",
run() {
console.log("cat run");
},
};
const fishObj = {
name: "fish",
swim() {
console.log("fish run");
},
};
console.log(isFish(catObj)); // false
console.log(isFish(fishObj)); // ture
console.log(swimAsFish(catObj)); // error
console.log(swimAsAny(catObj)); // error
ts类型断言
最新推荐文章于 2024-08-01 11:08:20 发布