microsoft / microsoft/TypeScript

[Regression] Failed to assign to a discriminated union class property when its type is inferred from constructor

Open
#60,394 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Type Inference Help Wanted
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms

property infer constructor discriminated

🕗 Version & Regression Information
  • This changed between versions 4.3.5 and 4.4.4 (also in latest)
⏯ Playground Link

https://www.typescriptlang.org/play/?ts=4.4.4#code/C4TwDgpgBAysCGxoF4oG8qkgLigcgCcBXAOxIEsSBzPAGigGdIIATXEogWwCMICoAvlAA+6TOAi48DYAHswkFnkEBuAFBqAxgBt4DBlACCmufzRqolqGALkAbomgzH6q1AD07t1YB6Afg03TVkSGWITWQIACgBKdAtvS2AAC3IGADpnJChUDCxJfBl5RWUhPVgEJFcrAUCrYhIopghWdi5eAjjzRKTUjKyUMXypBopqOkZmFkEEy1qBIA

💻 Code
type State = { type: 'running', speed: number } | { type: 'stopped' };

class Actor {
    private state;
    //       ^? Actor.state: State

    constructor() {
        this.state = { type: 'stopped' } as State;
    }

    run(speed: number) {
        this.state = { type: 'running', speed }
    }
}
🙁 Actual behavior

Type 'string' is not assignable to type '"running" | "stopped"'.(2322)

🙂 Expected behavior

No error, as in 4.3.5.

Additional information about the issue

If the property's type is explicitly declared as private state: State the error is gone.

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 repro and compare its behavior in 4.3.5, 4.4.4, and the latest version. Investigate inferred class-property types and assignment checking for the discriminated union shown. Done means the repro no longer reports an error without an explicit property annotation, with a regression test covering the case.

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.