Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
chriskrycho opened this issue Dec 21, 2017 · 2 comments
Closed

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

chriskrycho opened this issue Dec 21, 2017 · 2 comments

Comments

@chriskrycho
Copy link

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.

@jwbay
Copy link
Contributor

jwbay commented Dec 22, 2017

See #20503 for the most recent request for the same.

@chriskrycho
Copy link
Author

My search-fu is the worst.

@microsoft microsoft locked and limited conversation to collaborators Jun 21, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants