Microsoft/TypeScript

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

Open

#60,394 建立於 2024年11月2日

在 GitHub 查看
 (1 留言) (0 反應) (0 負責人)TypeScript (6,726 fork)batch import
BugDomain: check: Type InferenceHelp Wanted

倉庫指標

Star
 (48,455 star)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 9 個 PR)

描述

🔎 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.

貢獻者指南