typescript 类型对象上不存在属性“地图”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39685450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:52:41  来源:igfitidea点击:

Property 'map' does not exist on type Object

typescript

提问by kraftwer1

type MyStructure = Object[] |?Object;

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

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

The library either delivers an object or an array of this object. How can I type this?

该库要么提供一个对象,要么提供此对象的数组。我怎样才能输入这个?

EDIT

编辑

And how can I access properties like myStructure["foo"]in case of myStructurewill be an object?

我怎样才能访问性能,如myStructure["foo"]在案件的myStructure将是一个对象呢?

回答by Fenton

Because your type means you could have an object, or you could have an array; TypeScript can't determine which members are appropriate.

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

To test this out, change your type and you'll see the mapmethod is now available:

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

type MyStructure = Object[];

In your case, the actual solution will be to use a type guard to check that you have an array before attempting to use the mapmethod.

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

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

You could also solve your problem using a slightly different definition of MyStructure, for example:

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

type MyStructure = any[] | any;

Or the narrower:

或者更窄:

class Test {
    foo: string;
}

type MyStructure = Test[] | Test;