類型保護
1、類型斷言的方式
interface Bird {
fly: boolean;
sing: () => {};
}
interface Dog {
fly: boolean;
bark: () => {};
}
// 類型斷言的方式
function trainAnial(animal: Bird | Dog) { // 使用 | 就是聯(lián)合類型
if (animal.fly) {
// animal.sing(); // 錯誤 因為typescript不知道animal是否有sing方法
(animal as Bird).sing(); // 正確 使用類型斷言
} else {
(animal as Dog).bark();
}
}
2井厌、in 語法做類型保護
interface Bird {
fly: boolean;
sing: () => {};
}
interface Dog {
fly: boolean;
bark: () => {};
}
function trainAnialSecond(animal: Bird | Dog) {
if ('sing' in animal) {
animal.sing();
} else {
animal.bark();
}
}
3蚓庭、typeof 方式
function add(first: string | number, second: string | number) {
return first + second; // 錯誤 string不能使用 + 操作符
}
// 正確
function add(first: string | number, second: string | number) {
if (typeof first === 'string' || typeof second === 'string') {
return `${first}${second}`;
}
return first + second;
}
4、instanceof 方式
class NumberObj {
count: number;
}
// 錯誤
function addSecond(first: object | NumberObj, second: object | NumberObj) {
return first.count + second.count; // count不一定存在旗笔,因為first和second可能是NumberObj或者其他對象
}
// 正確
function addSecond(first: object | NumberObj, second: object | NumberObj) {
if (first instanceof NumberObj && second instanceof NumberObj) {
return first.count + second.count;
}
return 0;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者