使用"in"进行的类型缩小无法按预期工作



我正试图缩小TypeScript的类型,比如:

const result = await fetch('example.com')
if (typeof result === "object" && "errors" in result) {
console.error(result.errors);
}

因此,为了明确if之前的结果类型应该是unknown

然而我的ide告诉我TS2339: Property 'errors' does not exist on type 'object'.

在我看来,TS似乎忽略了in关键字。我把typeof result === "object"放在那里,首先检查我是否可以使用in

奇怪的是,当我这样做时,我的IDE没有抱怨:

if (typeof result === "object" && "errors" in result) {
console.error(result["errors"]);
}

但TS似乎没有检查这个,因为我也没有收到任何投诉:

if (typeof result === "object" && "errors" in result) {
console.error(result["nothere"]);
}

有人能帮我解释一下吗?

in运算符不会让您"添加";现有类型的键。

您必须明确地告诉编译器密钥可能存在:

const result: Response & { errors?: unknown } = await fetch('example.com')
if (typeof result === "object" && "errors" in result) {
console.error(result.errors);
}

游乐场

相关内容

最新更新