- 类型守卫: typeof(number,string,boolean,object,function,undefined)
-
类型缩小:等值类型缩小(===,!==,==,!=作为判断条件的),in操作符缩小,instanceof操作符缩小,真值缩小('',undefined,null,NaN,0),分配缩小。
image.png
type Fish = {swim:()=>void}
type Bird = {fly:()=>void}
function move(animal:Fish|Bird){
if('swim' in animal){
return animal.swim();
}
return animal.fly();
}
image.png
- 类型谓词:is:用户自定义类型保护。
// 通过泛型定义通用类型保护函数
function isOfType<T>(
target: unknown,
prop: keyof T
): target is T {
return (target as T)[prop] !== undefined;
}
网友评论