Skip to content

T[keyof T] type constraint lost in function body #12991

Closed
@jaredru

Description

@jaredru

TypeScript Version: 2.1.4 / nightly (2.2.0-dev.20161216)

function fn<T extends {[P in K]: string}, K extends keyof T>(obj: T, key: K) {
  const val: string = obj[key];  // error TS2322: Type 'T[K]' is not assignable to type 'string'
}

fn({ str: "s", num: 1 }, "str"); // OK
fn({ str: "s", num: 1 }, "num"); // error TS2345: Argument of type '{ str: string; num: number; }' is not assignable to parameter of type '{ num: string; }

Expected behavior:

Given the constraints, I would expect obj[key] in this case to be of type string.

Actual behavior:

The type of obj[key] is the less specific T[K].

Considering the error at the second call site (which is expected), it seems that the type checking done there is complete and working. However, that same type info is not carried through into the function body itself.

Metadata

Metadata

Assignees

No one assigned

    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

    Issue actions