-1

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.

2

2 Answers 2

1

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"
}]
Sign up to request clarification or add additional context in comments.

2 Comments

[ {[key: string]: string} ] is definitely an Array, but only with one element inside of it ;)
@MikeS. TS calls that a tuple. Yes, it accepts an array for it but the type itself has a distinct name.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.