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

Type inference with for...in #13046

Closed
johnfn opened this issue Dec 20, 2016 · 3 comments
Closed

Type inference with for...in #13046

johnfn opened this issue Dec 20, 2016 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@johnfn
Copy link

johnfn commented Dec 20, 2016

I would expect the following code to typecheck and work:

const x = { a : 1, b : 2 };

for (const foo in x) {
    console.log(x[foo]);
}

However, it gives an error that x has no index signature.

The problem appears to be that foo is not inferred to be of type keyof (typeof x). If I do the following, there are no errors:

const x = { a : 1, b : 2 };

for (const foo in x) {
    console.log(x[foo as keyof (typeof x)]);
}

Shouldn't x be inferred to be that type?

(Apologies if this issue already exists somewhere. I searched pretty hard and I could not find it.)


It also seems weird that something like this infers the type of foo properly. We have less information about x, yet our type constraint on x is stricter.

function test<T>(x: T) {
    for (const foo in x) {
        console.log(x[foo]);
    }
}
@RyanCavanaugh
Copy link
Member

#12314, #12988

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Dec 21, 2016
@johnfn
Copy link
Author

johnfn commented Dec 21, 2016

Ah, that's pretty tough for something which developers do all the time.

Are there any workarounds for iterating over and indexing an object in a typesafe manner? One I see is to give all my types index signatures, but I have a habit of defining object literals and allowing the type inference to take over.

@RyanCavanaugh
Copy link
Member

any (non-strict) or { [k: string]: { } } (strict) are the types you should assert x to in this case.

Since we don't know (in general) that x doesn't actually reference a subtype with other keys of different types, there's no known-correct type for us to produce for x[k] in a for(k in x).

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 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