主播之前做项目的时候用过TS,但没有系统地学习过,最近看文档注意到了以前没用过的语法和细节,记录一下。
类型守卫
众所周知TS最伟大的功能之一就是可以有类型保护机制,可以尽早发现代码中的类型错误。除了用as或in缩小类型,is关键字(类型谓词)也可以用来实现类型守卫。
如何使用
具体用法把类型谓词是作为判断类型的函数的返回值,belike:
function isString(test: any): test is string {
return typeof test === 'string';
}
function beUpperCase(str: any): string {
if (isString(str)) {
return str.toUpperCase();
}
return str + ' is not a string';
}
console.log(beUpperCase('hello')); // HELLO
进行类型断言之后,test的类型就会从any被缩窄为string,从而只能调用string的方法。
除了可以断言js自带的类型,也可以用来断言自定义类型:
type Fish = { swim: () => void };
type Bird = { fly: () => void };
declare function getSmallPet(): Fish | Bird;
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
// “swim”和“fly”的调用现在都没问题。
let pet = getSmallPet();
if (isFish(pet)) {
pet.swim();
} else {
pet.fly();
}
与Boolean的区别
如果只是判断参数是否是某种类型,返回值用Boolean就行了,为什么还要用is呢?因为boolean并不能真正进行类型收窄,后续调用相关方法会报错。
比如初始类型是联合类型,想收窄成其中的某一种,后续调用这种类型的方法时,理论上没问题,但ts会报错;如果初始类型是any,想收窄成string,但后续调用了number的方法,ts也不会发现异常,可以正常编译,但运行会报错。