typescript进阶
作者:互联网
环境准备
参考基础《TODO》
联合类型和类型保护
interface Bird {
fly: boolean;
sing: () => {};
}
interface Dog {
fly: boolean;
bark: () => {};
}
// 联合类型
function trainAnimal(animal: Bird | Dog) {
if (animal.fly) {
// 1、类型断言
(animal as Bird).sing();
}
}
function trainAnimal2(animal: Bird | Dog) {
// 2、in || typeof || instanceof
if ("sing" in animal) {
animal.sing;
}
}
标签:fly,typescript,进阶,Dog,boolean,animal,sing,Bird 来源: https://www.cnblogs.com/shzcs/p/16186946.html