Skip to content

Object.keys return string[] instead of keyof type #20853

@chriskrycho

Description

@chriskrycho

TypeScript Version: 2.6.2 (but tsc isn't the problem here; the typings are).

Code

function getValue<T, K extends keyof T>(obj: T, a: K): T[K] {
  return obj[a];
}

const foo = { a: true };
const keys = Object.keys(foo);
getValue(foo, keys[0]);

Expected behavior:

This should type-check!

Actual behavior:

Argument of type 'string' is not assignable to parameter of type '"a"'.

The obvious solution here is to make the type definition for Object.keys return keyof property, and I'm happy to submit that small PR to the appropriate lib files:

// within the Object type definition
keys<T, K extends keyof T>(o: T): K[];

This automatically works everywhere that Object.keys works today because (keyof T)[] is always a proper subtype of string[].

This resolves it nicely. However, I'm unsure what the relationship between the versions of the typings in lib here and TS versions is – do they need to be backwards compatible to previous versions of TS? Otherwise, as noted, I'll happily open that PR.

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