Typescript断言条件未缩小已知联合类型

Typescript断言条件未缩小已知联合类型,typescript,Typescript,以下断言条件没有将值类型缩小为{[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))

以下断言条件没有将
类型缩小为
{[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"])
typemyunion={[key:string]:any}| string[];
函数assertObject(值:any):断言值为记录{
if(value==null | | type of value!==“object”| | Array.isArray(value)){
抛出新错误(“断言失败”);
}
}
函数getValue():MyUnion{
返回{foo:“bar”};
}
const value=getValue();
资产对象(价值);
//错误,因为它不知道它是字符串[]还是{[key:string]:any}
console.log(值[“propName”])
游乐场连接:


似乎与以下内容有关:

因为
string[]
{[key:string]:any}
的子类型,断言不能缩小它的范围。

因为
string[]
{[key:string]:any}
的子类型,断言不能缩小它的范围。

是的。那绝对是个错误!是的。那绝对是个错误!