0

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.

2 Answers 2

1

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

So in your case

export type trollType = { [key: string]: string }[];
Sign up to request clarification or add additional context in comments.

Comments

0

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'
      }
    ];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.