I want to create a type for an array of objects. The array of objects can look like this:
JavaScript
x
11
11
1
const troll = [
2
{
3
a: 'something',
4
b: 'something else'
5
},
6
{
7
a: 'something',
8
b: 'something else'
9
}
10
];
11
the type i am trying to use is:
JavaScript
1
2
1
export type trollType = [{ [key: string]: string }];
2
Then i want to use the type like this:
JavaScript
1
11
11
1
const troll: trollType = [
2
{
3
a: 'something',
4
b: 'something else'
5
},
6
{
7
a: 'something',
8
b: 'something else'
9
}
10
];
11
but i get this error:
JavaScript
1
3
1
Type '[{ a: string; b: string; }, { a: string; b: string; }]' is not assignable to type 'trollType'.
2
Source has 2 element(s) but target allows only 1
3
I can do something like this:
JavaScript
1
2
1
export type trollType = [{ [key: string]: string }, { [key: string]: string }];
2
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
JavaScript
1
2
1
export type trollType = { [key: string]: string }[];
2