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

Suggestion: Better typing for key in "for in" loop. #19137

Closed
mpawelski opened this issue Oct 12, 2017 · 4 comments
Closed

Suggestion: Better typing for key in "for in" loop. #19137

mpawelski opened this issue Oct 12, 2017 · 4 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@mpawelski
Copy link

I noticed that in generic functions when we use for in loop on object of type T then iterator element is of type keyof T

function testForIn<T>(obj: T) {    
    for (let key in obj) {
        obj[key]; //key: keyof T
    }    
}

But for normal code on not generic object types we always get string as type of key variable:

let example: Example = { propNumber: 1, propString: "foo" };
for (let key in example) {
    let value = example[key];
}

And in this example we'll get any as type of value and error when we'll use noImplicitAny

Suggestion:

Can't we infer the type of key as keyof typeof example which is "propString" | "propNumber". It looks more consistent with generics behavior.

Of couse right now we can do workaround like this:

let example: Example = { propNumber: 1, propString: "foo" };
for (let key in example) {
    let k = key as keyof typeof example;
    let value = example[k];
}

But is it necessary? If key was properly inferred then we would have better typing (no any type when indexing) with no unnecessary additional type annotation.

@mhegazy
Copy link
Contributor

mhegazy commented Oct 12, 2017

The behavior is intentional, same reasoning as #13989

@mhegazy mhegazy added the Working as Intended The behavior described is the intended behavior; this is not a bug label Oct 12, 2017
@mpawelski
Copy link
Author

Ok, this reasoning make sense.
But if we had something like exact types from flow (#12936) it would be valid feature to have, right?

@mhegazy
Copy link
Contributor

mhegazy commented Oct 13, 2017

yes.

@mhegazy
Copy link
Contributor

mhegazy commented Oct 27, 2017

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@mhegazy mhegazy closed this as completed Oct 27, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

2 participants