【发布时间】:2020-04-02 22:01:53
【问题描述】:
以下断言条件不会将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"])
【问题讨论】:
-
是的。这绝对是一个错误!
标签: typescript