Skip to content

Index Signature Defined to String but Accept Number #23328

Closed
@MrDesjardins

Description

@MrDesjardins

TypeScript Version: 2.8.3-insiders.20180407
(Also in the Playground)

Search Terms: index signature

Code

let x: string = "x";
x = 1; // As expected, this line doesn't compile

interface Obj { 
    [id: string]: boolean;
}
let y: Obj = {};
y["okay"] = true;
y[123] = false; // The id is set to string, why does it compiles?

Expected behavior:
The last line of the code, I would expect to have TypeScript to say the same error as the second line. The error should say that the index must be a string.

Actual behavior:
The code compiles without error even if it is mentioned that only string must be accepted.

Playground Link: https://www.typescriptlang.org/play/index.html#src=let%20x%3A%20string%20%3D%20%22x%22%3B%0Ax%20%3D%201%3B%20%2F%2F%20As%20expected%2C%20this%20line%20doesn't%20compile%0A%0Ainterface%20Obj%20%7B%20%0A%20%20%20%20%5Bid%3A%20string%5D%3A%20boolean%3B%0A%7D%0Alet%20y%3A%20Obj%20%3D%20%7B%7D%3B%0Ay%5B%22okay%22%5D%20%3D%20true%3B%0Ay%5B123%5D%20%3D%20false%3B%20%2F%2F%20The%20id%20is%20set%20to%20string%2C%20why%20does%20it%20compiles%3F

Related Issues: Couldn't find.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions