microsoft / microsoft/TypeScript

Only number index type is inferred from `any` computed property key

Open
#45,629 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: Index Types
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

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 }

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked TypeScript Playground reproduction and trace computed-property/indexer inference for an any key. Determine the intended inferred indexer type, then verify the result against the shown string access example and add or update coverage in the relevant type-checking tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.