Home > Back-end >  Crating a type of array of multiple objects
Crating a type of array of multiple objects

Time:06-15

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.

CodePudding user response:

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

So in your case

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

CodePudding user response:

You can try to use the Record type for storing the object attribute definitions and create an array out of it, like in the following:

type TrollType = Record<string, string>[];

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