Skip to content

Type 'any[]' is not assignable to type '[any, any]' when constructing a Map from array of entries  #22870

Closed

Description

@mohsen1

During my work at webpack/webpack#6862 I noticed this error.

TypeScript Version: 2.7.8-rc

Search Terms:

Code
https://github.com/webpack/webpack/blob/master/lib/util/objectToMap.js

function objectToMap(obj) {
	return new Map(Object.keys(obj).map(key => [key, obj[key]]));
};

Expected behavior:
No error

Actual behavior:


lib/util/objectToMap.js:9:17 - error TS2345: Argument of type 'any[][]' is not assignable to parameter of type 'Iterable<[any, any]>'.
  Types of property '[Symbol.iterator]' are incompatible.
    Type '() => IterableIterator<any[]>' is not assignable to type '() => Iterator<[any, any]>'.
      Type 'IterableIterator<any[]>' is not assignable to type 'Iterator<[any, any]>'.
        Types of property 'next' are incompatible.
          Type '{ (value?: any): IteratorResult<any[]>; (value?: any): IteratorResult<any[]>; }' is not assignable to type '{ (value?: any): IteratorResult<[any, any]>; (value?: any): IteratorResult<[any, any]>; }'.
            Type 'IteratorResult<any[]>' is not assignable to type 'IteratorResult<[any, any]>'.
              Type 'any[]' is not assignable to type '[any, any]'.
                Property '0' is missing in type 'any[]'.

9  return new Map(Object.keys(obj).map(key => [key, obj[key]]));
                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Activity

  1. DanielRosenwasser commented on Mar 26, 2018

    @DanielRosenwasser
    Member

    I think this looks like a duplicate of #11152.

  2. MartinJohns commented on Mar 26, 2018

    @MartinJohns
    Contributor

    The tuple is inferred to be an array. As a temporary workaround you can just specify the exact type when calling map:

    array.map<[Type1, Type2]>(key => [key, obj[key]])
    

    That will make it explicit that you want a tuple.

  3. mhegazy commented on Mar 26, 2018

    @mhegazy
    Contributor

    in a .js file you can cast using /** @type ... */:

    function objectToMap(obj) {
    	return new Map(Object.keys(obj).map(key => /** @type [string, string] */ ([key, obj[key]]));
    };  
  4. typescript-bot commented on Apr 10, 2018

    @typescript-bot
    Contributor

    Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

  5. locked and limited conversation to collaborators on Jul 25, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions