Skip to content

Structural assignability of mapped types when key type is generic #13274

Closed
@Igorbek

Description

@Igorbek

TypeScript Version: 2.1.4

Code

type M<K extends string> = { [P in K]: P; };

function f<K extends string>() {
    const a1 = null as any as ({ [P in K]: P; });
    const a2: { [P in K]: P; } = a1;
        //~~ Type '{ [P in K]: P; }' is not assignable to type '{ [P in K]: P; }'. Two different types with this name exist, but they are unrelated.

    // However, if a type definition is used
    const a3 = null as any as M<K>;
    const a4: M<K> = a3;
        //^^ OK
}

// when keyof is used, it works
function g<T>() {
    const a1 = null as any as ({ [P in keyof T]: P; });
    const a2: { [P in keyof T]: P; } = a1;
        //^^ OK
}

Expected behavior:

No error.

Actual behavior:

Error:

Type '{ [P in K]: P; }' is not assignable to type '{ [P in K]: P; }'. Two different types with this name exist, but they are unrelated.
  Type 'P' is not assignable to type 'P'. Two different types with this name exist, but they are unrelated.
    Type 'K' is not assignable to type 'P'.
      Type 'string' is not assignable to type 'P'.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions