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(...in...) with mapped types cannot see index type (noImplicitAny) #14451

Closed
jameswilddev opened this issue Mar 4, 2017 · 4 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@jameswilddev
Copy link

jameswilddev commented Mar 4, 2017

TypeScript Version: 2.2.1
Code

// noImplicitAny must be enabled.

type Options = "A" | "B" | "C"
const MappedOptions: {[option in Options]: number } = {
    A: 2,
    B: 3,
    C: 4
}

for (const key in MappedOptions) {
    alert(MappedOptions[key])
}

Expected behavior:
This compiles, as the index type of MappedOptions is Options.

Actual behavior:
A compile-time error occurs as MappedOptions has no index signature.

@ikatyang
Copy link
Contributor

ikatyang commented Mar 5, 2017

The type of key is considered a string, you have to convert it to Options manually, since there is no index signature, e.g. { [key: string]: number }.

solution:

for (const key in MappedOptions) {
  alert(MappedOptions[<Options>key]);
}

or

Object.keys(MappedOptions).forEach((key: Options) => {
  alert(MappedOptions[key]);
});

I recommend the second one since it is clearer.

@jameswilddev
Copy link
Author

Thanks. I'm already doing that (MappedOptions[key as Options]).

@RyanCavanaugh RyanCavanaugh added the Needs Investigation This issue needs a team member to investigate its status. label May 24, 2017
@mhegazy
Copy link
Contributor

mhegazy commented Feb 9, 2018

Duplicate of #20503 or at least the same rational why it works this way. Please see #12253 (comment) for more context.

@mhegazy mhegazy added Duplicate An existing issue was already created and removed Needs Investigation This issue needs a team member to investigate its status. labels Feb 9, 2018
@typescript-bot
Copy link
Collaborator

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

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

5 participants