物业'地图'在Object类型上不存在

时间:2016-09-25 09:41:11

标签: typescript

type MyStructure = Object[] | Object;

const myStructure: MyStructure = [{ foo: "bar" }];

myStructure.map(); // Property 'map' does not exist on type 'MyStructure'. any

库提供此对象的对象或数组。我怎么输入这个?

修改

如果myStructure["foo"]将成为对象,我该如何访问myStructure等属性?

1 个答案:

答案 0 :(得分:5)

因为你的类型意味着你可以有一个对象,或者你可以拥有一个数组; TypeScript无法确定哪些成员是合适的。

要对此进行测试,请更改您的类型,您会看到map方法现已可用:

type MyStructure = Object[];

在您的情况下,实际的解决方案是在尝试使用map方法之前使用类型保护来检查您是否有数组。

if (myStructure instanceof Array) {
    myStructure.map((val, idx, []) => { });
}

您也可以使用稍微不同的MyStructure定义来解决您的问题,例如:

type MyStructure = any[] | any;

或者更窄:

class Test {
    foo: string;
}

type MyStructure = Test[] | Test;
相关问题