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 string is assignable to interface with index signature from number to string #41228

Closed
vostrnad opened this issue Oct 25, 2020 · 1 comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@vostrnad
Copy link

TypeScript Version: 4.1.0-beta

Search Terms: string assignable index signature number

Code

interface NumberIndexable {
  [index: number]: string;
}

function setValueAtIndex(object: NumberIndexable, index: number, value: string) {
  object[index] = value;
}

setValueAtIndex({}, 0, 'test'); // works fine
setValueAtIndex('oops', 0, 'test'); // runtime error

Expected behavior:

Second call to setValueAtIndex should raise a compiler error.

Actual behavior:

No compiler error is raised, which results in a runtime error because string indeces are read-only.

Playground Link: Playground

@MartinJohns
Copy link
Contributor

string being assignable to your type is correct and working as intended. A string can be accessed with an index signature.

The problem stems from TypeScript not distinguishing between readonly and mutable types, or no way to specify immutability in the type-system. The immutable type string should not be assignable to a mutable interface. Issues to track this would be #18770 and #10725.

@RyanCavanaugh RyanCavanaugh added the Design Limitation Constraints of the existing architecture prevent this from being fixed label Oct 26, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

3 participants