打字稿断言条件不缩小已知联合类型

时间:2020-03-18 11:42:47

标签: typescript

以下声明条件没有将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"])

游乐场链接:http://www.typescriptlang.org/play/#code/C4TwDgpgBAsiCqA7Alge0VAvFA3lA2gNYQgBcUAzsAE7KIDmAuuQIaIhQC+UAPpTXXr5GAbgBQYgGYBXRAGNgaDCwoUI1YAHkARgCsICgBQA3FgBtpEVuwCUrVeuAUopi9GTOASgdTUAJgA8VLQMADRQbCAAfLhiUPFQyJJQJuaWWJjYiNJmZrx8oJCoya7pAISZUABEqHoGwFX5UACC1NQsIAB0Hq3tIKluNjaxCaNQwAAW1KgA7lCIEHMAom2+hlXNDhpKUJIsyGYQflU24qOcYhdSsgo79BDAAGppEIZ2sAgo6CMJ1A-S1AweEkqFQ5Cq2hY1EanHEVzk6CoLheWCg9yeLze4jEKjUGh0+iMpQgpwkCMQFFQh06ZlQ9AGlnwVTA0zAADkWABbCBVRg2IA

似乎与https://github.com/microsoft/TypeScript/issues/37241

有关

1 个答案:

答案 0 :(得分:0)

由于string[]{ [key: string]: any }的子类型,因此断言无法缩小其范围。