Skip to content

ES6 Map array constructor needs extra hints #8936

Closed
@johnnyreilly

Description

@johnnyreilly

TypeScript Version:

1.8.10

Code

        const iAmAnArray [
        { value: "value1", text: "hello" }
        { value: "value2", text: "map" }
        ];
        const iAmAMap = new Map<string, string>(
            iAmAnArray.map(x => [x.value, x.text])
        );

Expected behavior:
I would expect this to be working code.

Actual behavior:
It errors with:

[ts] Argument of type 'string[][]' is not assignable to parameter of type 'Iterable<[string, string]>'.
  Types of property '[Symbol.iterator]' are incompatible.
    Type '() => IterableIterator<string[]>' is not assignable to type '() => Iterator<[string, string]>'.
      Type 'IterableIterator<string[]>' is not assignable to type 'Iterator<[string, string]>'.
        Types of property 'next' are incompatible.
          Type '(value?: any) => IteratorResult<string[]>' is not assignable to type '(value?: any) => IteratorResult<[string, string]>'.
            Type 'IteratorResult<string[]>' is not assignable to type 'IteratorResult<[string, string]>'.
              Type 'string[]' is not assignable to type '[string, string]'.
                Property '0' is missing in type 'string[]'.

If I give the compiler a clue using as [string, string] this becomes working code:

        const iAmAnArray [
        { value: "value1", text: "hello" }
        { value: "value2", text: "map" }
        ];
        const iAmAMap = new Map<string, string>(
            iAmAnArray.map(x => [x.value, x.text] as [string, string])
        );

Is there a reason that we have to tell the compiler specifically what we we're pushing out? (ie an array with 2 entries)

I can do this but it's not obvious; I've found no documentation anywhere on this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions