类型保护
断言
instanceof 一般是用在class 这种对象上的,不能用在基本类型上,基本类型使用typeof 。
// 类型断言
const lengthFun = (a: string | number) => {
return (a as string).length; // 一般不使用<>做断言,是因为会和Reat 语法冲突。
}
// 类型断言,不到万不得已不要用,因为使用断言就失去了ts 自动推断类型和使用类型限制的意义。
// 类型保护typeof 和 instanceof
// typeof
const lengthFun1 = (a: string | number): number => {
if(typeof a === 'string') {
return a.length;
}
if(typeof a === 'number') {
return a.toString().length;
}
return 0;
}
// instanceof
class Man {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
class Woman {
gender: string;
tel: number;
constructor(gender: string, tel: number) {
this.gender = gender;
this.tel = tel;
}
}
const Fun = (a: Man | Woman): (string | number) => {
if(a instanceof Man) {
return a.name;
}
if(a instanceof Woman) {
return a.tel;
}
return 666;
}