Typescript: Construct new Map from Array results in error TS2345

Created on 24 Nov 2016  路  3Comments  路  Source: microsoft/TypeScript



TypeScript Version: 2.1.1

Code

new Map([
  ['a', {
    prop: {}
  }],
  ['b', { }]
]);

Expected behavior:

Creates a new Map with the keys a and b.

Actual behavior:

Error:(10, 9) TS2345:Argument of type '((string | { prop: {}; })[] | {}[])[]' is not assignable to parameter of type 'IterableShim<[{}, {}]>'.
  Types of property '"_es6-shim iterator_"' are incompatible.
    Type '() => IterableIteratorShim<(string | { prop: {}; })[] | {}[]>' is not assignable to type '() => Iterator<[{}, {}]>'.
      Type 'IterableIteratorShim<(string | { prop: {}; })[] | {}[]>' is not assignable to type 'Iterator<[{}, {}]>'.
        Types of property 'next' are incompatible.
          Type '{ (value?: any): IteratorResult<(string | { prop: {}; })[] | {}[]>; (value?: any): IteratorResult...' is not assignable to type '{ (value?: any): IteratorResult<[{}, {}]>; (value?: any): IteratorResult<[{}, {}]>; (value?: any)...'.
            Type 'IteratorResult<(string | { prop: {}; })[] | {}[]>' is not assignable to type 'IteratorResult<[{}, {}]>'.
              Type '(string | { prop: {}; })[] | {}[]' is not assignable to type '[{}, {}]'.
                Type '(string | { prop: {}; })[]' is not assignable to type '[{}, {}]'.
                  Property '0' is missing in type '(string | { prop: {}; })[]'.

Most helpful comment

TypeScript cannot contextually infer the array literal you are passing it to determine the generic properties for for the newly create Map. The easiest solution is to supply them yourself, and then TypeScript determines if the passed array is assignable to that:

new Map<string, any>([
  ['a', {
    prop: {}
  }],
  ['b', { }]
]);

You could also type the array literal in a way that allows TypeScript to figure out what goes into each of the generic slots:

new Map(<[string, any][]> [
  ['a', {
    prop: {}
  }],
  ['b', { }]
]);

All 3 comments

TypeScript cannot contextually infer the array literal you are passing it to determine the generic properties for for the newly create Map. The easiest solution is to supply them yourself, and then TypeScript determines if the passed array is assignable to that:

new Map<string, any>([
  ['a', {
    prop: {}
  }],
  ['b', { }]
]);

You could also type the array literal in a way that allows TypeScript to figure out what goes into each of the generic slots:

new Map(<[string, any][]> [
  ['a', {
    prop: {}
  }],
  ['b', { }]
]);

Thanks a lot.
I would prefer that the compiler is detecting the property types but this fixes the problem.

@kitsonk

Thanks 'new Map(<[string, string][]>...' ended a period of frustration

let headers: Map = new Map(<[string, string][]>[
["Accept", "application/json"],
["Authorization", "Bearer XXXX"]
]);

Was this page helpful?
0 / 5 - 0 ratings