简单的例子:
const isString = (any: any): boolean => (typeof any === 'string')
function something(foo: string | number): string {
const value = isString(foo) ? foo : Number.prototype.toFixed.call(foo)
// ... какие-то действия
return value
}
在第一行之后,在函数内部,错误立即发光。TypeScript 无法正确处理带有自定义isString(foo)常量的字符串value,它将其视为string | number.
如果您typeof像这样明确使用和编写...
function something(foo: string | number): string {
const value = typeof foo === 'string' ? foo : Number.prototype.toFixed.call(foo)
return value
}
...然后const value: string分别没有错误。
强制安装,如...
/** @type {string} */
const value = ...
……也无济于事。
我找不到任何可以修复此行为的配置设置。

https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates