I have an interface that accepts { [key:string]: string }
.
I want to test several cases for it. For this I want to define an array containing my test cases as follows:
const tests: [ {[key: string]: string} ] = [{
"A": "B"
}, {
"C": "D"
}]
But it will not compile because Typescript is assuming those inline objects are types in of themselves.
Type '[{ A: string; }, { C: string; }]' is not assignable to type '[{ [key: string]: string; }]'. Source has 2 element(s) but target allows only 1.
CodePudding user response:
This is not how you type arrays of a particular type in TypeScript. The following gives no errors in the playground:
const tests: {[key: string]: string}[] = [{
"A": "B"
}, {
"C": "D"
}]
CodePudding user response:
It should be like this:
const tests: {[key: string]: string}[] = [{
"A": "B"
}, {
"C": "D"
}]
Doing it like you did, [{[key: string]: string}]
, means it should be an array with one object inside.