[英]Typescript assert condition not narrowing known union type
以下断言条件不会将value
类型缩小为{ [key: string]: any}
。 如何实现?
type MyUnion = { [key: string]: any } | string[];
function assertObject(value: any): asserts value is Record<string, any> {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
throw new Error("Assertion failed");
}
}
function getValue(): MyUnion {
return { foo: "bar" };
}
const value = getValue();
assertObject(value);
// Error as it does not know if it is a string[] or { [key: string]: any }
console.log(value["propName"])
似乎与: https : //github.com/microsoft/TypeScript/issues/37241有关
由于string[]
是{ [key: string]: any }
的子类型,断言不能缩小范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.