Skip to content

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

Closed
@pablobirukov

Description

@pablobirukov

TypeScript Version: [email protected], [email protected]

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions