类型保护正在删除字符串文字类型



创建TS类型保护时,将undefinednull添加到谓词类型后,字符串文字似乎会从收缩类型中删除。有什么方法可以使用具有类似x is 'my-string' | undefined的谓词的类型保护吗?

或者,换句话说:假设我们有一个谓词为x is 'my-string'的类型保护。每当使用此保护检查变量时,TS都会正确地将传递的变量缩小为文本类型'my-string'。但是,一旦将谓词更改为x is 'my-string' | undefined,TS就会将被检查变量的类型缩小为undefined。我原以为是'my-string' | undefined。为什么?类型保护不是用来检查字符串文字的吗?

示例:在TS游乐场中打开

/*
When using "typeGuard1", you will notice that the guarded type, for some reason, gets narrowed down to `undefined`.
It works fine with "typeGuard2".
*/
function typeGuard1(x: any): x is 'some-literal-string-type' | undefined {
return true;
}
function typeGuard2(x: any): x is string | undefined {
return true;
}
// The following setup is used to make sure the compiler does not magically infer anything.
const foo = getFoo();
function getFoo(): string | undefined {
if (Math.random() > 0.5) {
return 'This is foo'
}
return undefined;
}
if (typeGuard1(foo)) {
// For some reason, `foo` gets narrowed down to `undefined`. This does not happen if you use `isFoo2(foo)`, or if you remove "| undefined" from "typeGuard1".
console.log(foo?.length);
}
if (typeGuard2(foo)) {
console.log(foo?.length);
}

这是一个已知的错误,请参阅microsoft/TypeScript#31156。它已经在microsoft/TypeScript#49625中修复,应该与TypeScript 4.8一起发布。一旦发生这种情况,您的代码将按预期工作:

游乐场链接到使用TS版本4.8.0-dev.20220809 的代码

相关内容

最新更新