Microsoft/TypeScript

Incorrect error message on invalid union type assignation

Open

#55.465 geöffnet am 22. Aug. 2023

Auf GitHub ansehen
 (8 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)TypeScript (6.726 Forks)batch import
Experience EnhancementHelp WantedSuggestion

Repository-Metriken

Stars
 (48.455 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 6T 17h) (9 gemergte PRs in 30 T)

Beschreibung

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

Contributor Guide