Skip to content
Advertisement

Crating a type of array of multiple objects

I want to create a type for an array of objects. The array of objects can look like this:

   const troll = [
      {
        a: 'something',
        b: 'something else'
      },
      {
        a: 'something',
        b: 'something else'
      }
    ];

the type i am trying to use is:

export type trollType = [{ [key: string]: string }];

Then i want to use the type like this:

   const troll: trollType = [
      {
        a: 'something',
        b: 'something else'
      },
      {
        a: 'something',
        b: 'something else'
      }
    ];

but i get this error:

Type '[{ a: string; b: string; }, { a: string; b: string; }]' is not assignable to type 'trollType'.
  Source has 2 element(s) but target allows only 1

I can do something like this:

export type trollType = [{ [key: string]: string }, { [key: string]: string }];

but lets say my array of object will have 100 objects in the array.

Advertisement

Answer

When setting a type for an array it should in this format any[].

So in your case

export type trollType = { [key: string]: string }[];
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement