Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'map' does not exist on type Object

Tags:

typescript

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?

like image 203
kraftwer1 Avatar asked Sep 25 '16 09:09

kraftwer1


People also ask

Does not exist on type object?

The "Property does not exist on type Object" error occurs when we try to access a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names.

How do you type a map in TypeScript?

Use Map type and new keyword to create a map in TypeScript. let myMap = new Map<string, number>(); To create a Map with initial key-value pairs, pass the key-value pairs as an array to the Map constructor.

How do I fix TS2339 error?

To fix the error "TS2339: Property 'x' does not exist on type 'Y'" with TypeScript, we should make sure the properties are listed in the interface that's set as the type of the object. interface Images { main: string; [key: string]: string; } const getMainImageUrl = (images: Images): string => { return images.

Does not exist on type never TypeScript?

The error "Property does not exist on type 'never'" occurs when we try to access a property on a value of type never or when TypeScript gets confused when analyzing our code. To solve the error, use square brackets to access the property, e.g. employee['salary'] .


1 Answers

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, []) => { });
}

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

type MyStructure = any[] | any;

Or the narrower:

class Test {
    foo: string;
}

type MyStructure = Test[] | Test;
like image 165
Fenton Avatar answered Sep 30 '22 03:09

Fenton