microsoft / microsoft/TypeScript

Type Confusion when overwriting field on object creation

Open
#52,797 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Experimentation Needed Suggestion
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

🔎 Search Terms
  • "type confusion" -union label:Bug
  • object field -union label:Bug

... too many Bugs in this tracker to to more than skim the titles

🕗 Version & Regression Information

See in 4.9.5 after running into an example for this in a project.

The Playground also reproduces it in 3.3.3 and the 5.0.0 nightly.

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about object
⏯ Playground Link

[Playground link with relevant code](https://www.typescriptlang.org/play?ts=4.9.5#code/C4TwDgpgBAGlC8UDeUCGAuKBnYAnAlgHYDmANFAEaaECuAthRLlAL4BQbAxgPaE5SdcEVMGiIAFADN8EADYATAHKo6ETAGsIIbpNjlCEAO4BBavUa4AlJjjwAfMjZQoQ4DVyFkaTAHJUP8iooACZyAG1pOSUVCABdaiNjVjZ2Ll5+AA8EASERCHE-AJDLNL5uWQgAOlluYnFQSB0oDMrUSygAeg6oWgYmNiA

)

💻 Code
type X = { a: string, b: number }

const create = (fieldName: keyof X, newA: number): X => {
  return { a: 'a', b: 2, [fieldName]: newA }
}

const x = create('a', 2)
console.log(typeof x.a) // number
🙁 Actual behavior

The code survives typechecks and has a number in x.a.

🙂 Expected behavior

TypeScript rejecting code that assigns a number to a field typed as 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

The issue provides a TypeScript Playground reproduction but names no repository file or test. Start by running the example and tracing how the compiler checks the computed property in the object literal; it is done when TypeScript rejects the number assigned to the string field.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.