TypeScript 联合类型和类型保护
只有联合类型存在的情况下,才需要类型保护。类型保护又叫类型守护。
联合类型
interface Waiter {
anjiao: boolean;
say: () => {};
}
interface Teacher {
anjiao: boolean;
skill: () => {};
}
// animal 既可以是 Waiter 又可以是 Teacher,这就是联合类型
function judgeWho(animal: Waiter | Teacher) {}
四种类型保护
// 断言 as 语法
function judgeWho(animal: Waiter | Teacher) {
if (animal.anjiao) {
(animal as Teacher).skill();
}else{
(animal as Waiter).say();
}
}
// in 语法
function judgeWhoTwo(animal: Waiter | Teacher) {
if ("skill" in animal) {
animal.skill();
} else {
animal.say();
}
}
// typeof 语法
function add(first: string | number, second: string | number) {
if (typeof first === "string" || typeof second === "string") {
return `${first}${second}`;
}
return first + second;
}
// instanceof 语法,只能用在类上
class NumberObj {
count: number;
}
function addObj(first: object | NumberObj, second: object | NumberObj) {
if (first instanceof NumberObj && second instanceof NumberObj) {
return first.count + second.count;
}
return 0;
}

浙公网安备 33010602011771号