这是缺少TypeScript中的特性,还是考虑到TS编译器不能推断(然后缩小)参数的类型,如果条件逻辑被包装到单独的函数中?x.toUpperCase(); // ⚡️ x is still of type unknown}
但是,如果我去掉了isString函数,并在if语句中内联了它的逻辑,那么TS编译器就很清楚它的类型我知道我可以使用as string转换类型,或者使用类型谓词,并在isString函数中使用is string
} 然后像这样调用这个函数: function bar() { if (a === undefined) { }
return a; // TypeScript infers a as number (good!)} 因为函数foo返回元组(number, undefined)或(undefined, number),所以在没有通过a ===