warrenfitzhenry
warrenfitzhenry

Reputation: 2299

Typescript type Never[] not assignable to object array

I am trying to create an object array, for example:

objectExample[a].push({ id: john, detail: true });
objectExample[a].push({ id: james, detail: false});

const objectExample = {
   a = [ { id: john, detail: true}, 
         { id: james, detail: false}];
   }

If I try this in Typescript:

const objectExmaple: { [key: string]: { [key: string]: string | boolean}[]} = [];

I get this error on objectType:

Type 'never[]' is not assignable to type '{ [key: string]: { [key: string]: string | boolean; }[]; }'.
  Index signature is missing in type 'never[]'.ts(2322)

How do I get around this error?

Upvotes: 1

Views: 1355

Answers (2)

ThomasThiebaud
ThomasThiebaud

Reputation: 11969

There are a few problems:

  • You can't initialize objectExample to [] if it is an object
  • The type definition is complex for nothing
type Item = { [key: string]: string | boolean}
// Same as type Item = { [key: string]: string | boolean}

const objectExample: Record<string, Item[]> = {
   a: [ { id: 'john', detail: true}, 
         { id: 'james', detail: false}]
}

objectExample.a.push({ id: 'john', detail: true });
objectExample.a.push({ id: 'james', detail: false});

Here is a link to a working playground

Upvotes: 1

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249536

objectExmaple is an object, not an array, so you need to initialize it using {}. Also if you want for key a to have an array you will need to put that it either at init or before using push:

const objectExmaple: { [key: string]: { [key: string]: string | boolean }[] } = {
  a: []
};

objectExmaple['a'].push({ id: 'john', detail: true });
objectExmaple['a'].push({ id: 'james', detail: false});

Also the type could be written more legibly as Record<string, Array<Record<string, string | boolean>>>

Play

Upvotes: 1

Related Questions