Typescript 在判断 x != undefined 的时候,会同时判断 x != null,反之依然(x == undefined);同时,在判断 x != null 的时候,也会同时判断 x != undefined ,反之亦然。
functionfoo(x:number|null|undefined) {if (x !=null) {// x != null 实际上过滤掉了 null 和 undefined 两种情况// 因此 x 一定是 numberconsole.log(x.toFixed(2)) }}
自定义类型保护
我们可以自己封装一个判断函数,来判断某一变量是否为指定的类型
functionisString(test:string|number): test isstring {returntypeof test ==='string'}functionfoo(bar:any){if(isString(bar)){console.log("it's a string")console.log(bar.toFixed(2)) // 会在编译时报错,因为 bar 是 string }}
使用 <var> is <type> 谓词作为这个判断函数的返回值,ts 会在 if 逻辑后 narrow 它的类型
bar 已经从 any narrow 到 string 了,因此会直接报错
那么为什么不直接返回一个 boolean 呢?
functionisString(test:string|number):boolean {returntypeof test ==='string'}functionfoo(bar:any){if(isString(bar)){console.log("it's a string")console.log(bar.toFixed(2)) // 编译时不会报错,而 runtime 时会报错 }}
TypeScript 的 narrowing 机制需要借助 is 来实现,因此直接返回一个 boolean 并不可行