microsoft / microsoft/TypeScript

Type is not checked when using object spread and computed property of type `number`

Open
#43,698 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Excess Property Checking
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Bug Report

🔎 Search Terms

spread computed property number reduce

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
⏯ Playground Link

Playground link with relevant code

💻 Code
declare const id: number;

type Acc = { [key: string]: number };
declare const acc: Acc;

// Expected error, but got none. ❌
const acc2: Acc = {
    ...acc,
    [id]: 'invalid',
};

If we change the type of the computed property id from number to string, it works as expected (we get an error).

declare const id: string;

type Acc = { [key: string]: number };
declare const acc: Acc;

// Expected error, and got none. ✅
const acc2: Acc = {
    ...acc,
    [id]: 'invalid',
};

Alternatively, if we remove the spread of acc it works as expected:

declare const id: number;

type Acc = { [key: string]: number };
// declare const acc: Acc;

// Expected error, and got none. ✅
const acc2: Acc = {
    [id]: 'invalid',
};

My workaround for now is to convert the type before it's used as a computed property:

declare const id: number;

type Acc = { [key: string]: number };
declare const acc: Acc;

// Expected error, and got none. ✅
const acc2: Acc = {
    ...acc,
    [id.toString()]: 'invalid',
};
🙁 Actual behavior

See code comments above.

🙂 Expected behavior

See code comments above.

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 compare the cases using a numeric versus string computed property, with and without the object spread. Trace the type-checking behavior for the object literal and verify that the numeric-property case reports an error while the other examples retain their expected behavior.

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
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.