kraftwer1 kraftwer1 - 2 months ago 12
TypeScript Question

Property 'map' does not exist on type Object

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
myStructure
will be an object?

Answer

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

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

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 map method.

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