Microsoft/TypeScript

Incorrect error message on invalid union type assignation

Open

#55,465 建立於 2023年8月22日

在 GitHub 查看
 (8 留言) (0 反應) (0 負責人)TypeScript (6,726 fork)batch import
Experience EnhancementHelp WantedSuggestion

倉庫指標

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

描述

🔎 Search Terms

error message union type assignation

🕗 Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.2.1-rc#code/MYewdgzgLgBMBcMDeAPGiDkBDDMA+MGARrvocBgL4wC8yK82VMAUKJLEYqpjtQT0IlqdYAG4gA

💻 Code

const c: {x : 'a' | 'b'  | 'c'} = {x:'c'} 
const b: {x: 'a'} | {x: 'b'} = c;

🙁 Actual behavior

The error message is

Type '{ x: "a" | "b" | "c"; }' is not assignable to type '{ x: "a"; } | { x: "b"; }'.
  Type '{ x: "a" | "b" | "c"; }' is not assignable to type '{ x: "b"; }'.
    Types of property 'x' are incompatible.
      Type '"a" | "b" | "c"' is not assignable to type '"b"'.
        Type '"a"' is not assignable to type '"b"'.(2322)

The problem starts with the line Type '{ x: "a" | "b" | "c"; }' is not assignable to type '{ x: "b"; }'.. It is true that the types are incompatible, but it is not true that this is the source of the error.

In this simple case, it's easy to see where the actual problem is, but with large unions, it becomes hard to know where the error comes from.

🙂 Expected behavior

The actual problem is that type 'c' is not assignable to 'a' | 'b', and the error message should mention it. Maybe the full trace should look like this:

Type '{ x: "a" | "b" | "c"; }' is not assignable to type '{ x: "a"; } | { x: "b"; }'.
    Types of property 'x' are incompatible.
      Type '"a" | "b" | "c"' is not assignable to type '"a" | "b"'.
        Type '"c"' is not assignable to type '"a" | "b"'.(2322)

Additional information about the issue

When the unions are large and aliased, the misleading message makes errors hard to debug.

貢獻者指南