Skip to content

Assignment incompatibility with structurally equivalent generic mapped types #12832

Closed
@BigDataSamuli

Description

@BigDataSamuli

TypeScript Version: nightly (2.2.0-dev.20161211)

Code

type Mapped1<T> = {
  [P in keyof T]: T[P];
}

type Mapped2<T> = {
  [P in keyof T]: T[P];
}

function asMapped2<T>(a: Mapped1<T>): Mapped2<T> {
  return a;
}

Expected behavior:
No error.

Actual behavior:

test.ts(10,10): error TS2322: Type 'Mapped1<T>' is not assignable to type 'Mapped2<T>'.
  Type 'T[P]' is not assignable to type 'T[P]'. Two different types with this name exist, but they are 
unrelated.

Activity

ahejlsberg

ahejlsberg commented on Jan 3, 2017

@ahejlsberg
Member

Agreed. I think we need a rule that a mapped type { [P1 in K1] : X1 } is related to a mapped type { [P2 in K2]: X2 } when K1 is related to K2 and X1 is related to an instantiation of X2 that substitutes P1 for P2.

added this to the TypeScript 2.2 milestone on Jan 4, 2017
BigDataSamuli

BigDataSamuli commented on Jan 4, 2017

@BigDataSamuli
Author

FWIW, my original use case was similar to the following:

interface Fooify<T> {
  foo: T;
}

interface Barify<T> {
  bar: T;
}

type Mapped1<T> = {
  [P in keyof T]: Fooify<T[P]>;
}

type Mapped2<T> = {
  [P in keyof T]: Barify<T[P]> | Fooify<T[P]>;
}

function asMapped2<T>(a: Mapped1<T>): Mapped2<T> {
  return a;
}

which errors with

test.ts(18,10): error TS2322: Type 'Mapped1<T>' is not assignable to type 'Mapped2<T>'.
  Type 'Fooify<T[P]>' is not assignable to type 'Barify<T[P]> | Fooify<T[P]>'.
    Type 'Fooify<T[P]>' is not assignable to type 'Fooify<T[P]>'. Two different types with this name exist, but they are unrelated.
      Type 'T[P]' is not assignable to type 'T[P]'. Two different types with this name exist, but they are unrelated.

I presumed the issue in the OP is the underlying cause for this.

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

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

    Development

    No branches or pull requests

      Participants

      @ahejlsberg@BigDataSamuli@mhegazy

      Issue actions

        Assignment incompatibility with structurally equivalent generic mapped types · Issue #12832 · microsoft/TypeScript