Reputation: 961
I have an array like:
const myArray = [['key1', 'value1'], ['key2', 'value2']];
I want to create Map from myArray (In TypeScript, works fine in JS).
This does not work:
const myMap = new Map(myArray);
Error:
No overload matches this call.
Overload 1 of 3, '(iterable: Iterable<readonly [unknown, unknown]>): Map<unknown, unknown>', gave the following error.
Argument of type 'string[][]' is not assignable to parameter of type 'Iterable<readonly [unknown, unknown]>'.
...
But, this works:
const myMap = new Map([['key1', 'value1'], ['key2', 'value2']]);
Upvotes: 1
Views: 1342
Reputation: 371233
Typescript automatically infers the type of myArray
as:
string[][]
But the Map constructor only accepts iterables which contain arrays of exactly two items.
You can define the myArray
as const
so that TS doesn't automatically widen the type from "an array of arrays of 2 strings" to "an array of arrays of strings":
const myArray = [['key1', 'value1'], ['key2', 'value2']] as const;
Another way, for older versions of TS that don't support as const
(which was introduced in 3.4):
const myArray: Array<[string, string]> = [['key1', 'value1'], ['key2', 'value2']];
Or, if you need to preserve the keys/values exactly:
const myArray = [['key1', 'value1'] as ['key1', 'value1'], ['key2', 'value2'] as ['key2', 'value2']];
Upvotes: 7