TypeScript联合类型和类型保护
TypeScript在使用联合类型时,会遇到以下问题,需要进行类型保护,以保证逻辑严谨性。
// 联合类型
// 用于进行类型保护的方式
// 1. as 语法 - 类型断言
interface Bird {
fly: boolean;
sing: () => { };
}
interface Dog {
fly: boolean;
bark: () => { };
}
const trainAnimal = (animal: Bird | Dog) => {
animal.fly ? (animal as Bird).sing() : (animal as Dog).bark();
};
// 2. in 语法
const trainAnimalSecond = (animal: Bird | Dog) => {
'sing' in animal ? animal.sing() : animal.bark();
};
// 3. typeof 语法
const addData = (first: string | number, second: string | number) => {
return typeof first === 'string' || typeof second === 'string'
? `${ first}${ second}`
: first + second;
};
// 4. instanceof 语法
class NumberObj {
constructor(public count: number) { }
}
const addDataSecond = (
first: object | NumberObj,
second: object | NumberObj
) => {
return first instanceof NumberObj && second instanceof NumberObj
? first.count + second.count
: 0;
};
还没有评论,来说两句吧...