2016-09-25 102 views
1
type MyStructure = Object[] | Object; 

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

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

该库提供一个对象或该对象的数组。我怎样才能输入这个?属性'map'在类型上不存在

编辑

我怎样才能访问诸如myStructure["foo"]性质的myStructure情况下将是一个对象呢?

回答

0

因为你的类型意味着你可以有一个对象,或者你可以有一个数组; 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; 
+0

我实际上_.isArray这样做( ),这当然在TypeScript中不起作用...感谢您的帮助! – kraftwer1

+1

@索尼,你知道为什么这个作品'键入MyStructure = number [] |号码;'[Playground](https://www.typescriptlang.org/play/index.html#src=%0D%0Atype%20MyStructure%20%3D%20number%5B%5D%20%7C%20number%3B% 0D 0A%%0D%0Alet%20myStructure%3A%20MyStructure%20%3D%20%5B3%5D%3B%0D 0A%%0D%0AmyStructure.map(N%20%3D%3E%20N * 2)%3B %0D%0AmyStructure%20%3D%205%3B)? –

+0

这只是“对象”,会导致你的问题。参见另外两个使用'any'或者(可能更有用)示例的例子,它使用一个类来定义你在map方法中使用的任何东西(然后你会在你用来映射的函数中获得更好的类型信息)。 – Fenton

相关问题