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

for var key in object of interface should be keyof type #15092

Closed
greg-hornby-roam opened this issue Apr 9, 2017 · 1 comment
Closed

for var key in object of interface should be keyof type #15092

greg-hornby-roam opened this issue Apr 9, 2017 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@greg-hornby-roam
Copy link

greg-hornby-roam commented Apr 9, 2017

TypeScript Version: 2.2.2

Code

interface MyInterface {
  a: number;
  b: string;
  c: boolean;
}

var myObj: MyInterface = {a: 5, b: "foo", c: true};

for (var key in myObj) {
    var getValue = myObj[key];
}

Expected behavior:
The var key should have type keyof typeof myObj evaluating to 'a' | 'b' | 'c' instead of just string. This would then allow the use of myObj[key] without having to cast to any
ie (myObj as any)[key]

@DanielRosenwasser
Copy link
Member

Unfortunately this wouldn't be appropriate behavior - if you have a subtype of MyInterface (i.e. a type that's more specific than MyInterface), then the keys of myObj actually grow, which gives you a less specific type.

So you might think that at runtime your keys are a, b, and c, but in reality you might also have a d, e, and f property as well.

See #12892 for a similar discussion.

@DanielRosenwasser DanielRosenwasser added the Duplicate An existing issue was already created label Apr 13, 2017
@mhegazy mhegazy closed this as completed Apr 19, 2017
@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
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants