Skip to content

Only number index type is inferred from any computed property keyΒ #45629

Open

Description

Bug Report

πŸ”Ž Search Terms

  • Computed properties
  • Indexers
  • Index signatures

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

declare let a: any;

const obj = {
  [a]: "s",
}; // { [x: number]: string }

obj["abc"]; // error

πŸ™ Actual behavior

A numeric indexer is inferred. String index access marked as invalid.

πŸ™‚ Expected behavior

A string indexer is expected. No error for string access.

declare let a: any;

const obj = {
  [a]: "s",
}; // { [x: number]: string }

obj["abc"]; // no error

I created a small PR that addresses the issue as an example but I'm still not sure if the current behavior is intentional or not.

EDIT: I'm still not sure if the inferred indexer should have a String type, perhaps a union of the allowed primitive types fits better, e.g.:

declare let a: any;

const obj = {
  [a]: "s",
}; // { [x: string | number | symbol]: string }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions