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

Acces of object with index signature via key with generic type returns wrong type #22053

Closed
pablobirukov opened this issue Feb 20, 2018 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@pablobirukov
Copy link

pablobirukov commented Feb 20, 2018

TypeScript Version: typescript@2.8.0-dev.20180220, typescript@2.7.2

Code

declare const dict: { [K: string]: number | undefined };
function foo<S extends string>(betSpot: S): number {
    const value = dict[betSpot];
    return value ? value : 0;
//  ~~~~~~~~~~~~~~~~~~~~~~~~~
}

Expected behavior:

No error

Actual behavior:

Type '{ [K: string]: number | undefined; }[S]' is not assignable to type 'number'.
  Type 'number | undefined' is not assignable to type 'number'.
    Type 'undefined' is not assignable to type 'number'.

Playground Link: http://www.typescriptlang.org/play/index.html#src=declare%20const%20dict%3A%20%7B%20%5BK%3A%20string%5D%3A%20number%20%7C%20undefined%20%7D%3B%0D%0Afunction%20foo%3CS%20extends%20string%3E(betSpot%3A%20S)%3A%20number%20%7B%0D%0A%20%20%20%20const%20value%20%3D%20dict%5BbetSpot%5D%3B%0D%0A%20%20%20%20return%20value%20%3F%20value%20%3A%200%3B%0D%0A%7D

Related Issues:

#21770 #21760 seem related

@mhegazy
Copy link
Contributor

mhegazy commented Mar 10, 2018

looks like a duplicate of #22214

@mhegazy mhegazy added the Duplicate An existing issue was already created label Mar 10, 2018
@mhegazy
Copy link
Contributor

mhegazy commented Mar 10, 2018

dict[betSpot] is considered to be generic by the compiler, and thus not narrowed. but it does not have to be since dict has a string indexer.

@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 25, 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