Microsoft/TypeScript

Incorrect error message on invalid union type assignation

Ouverte

#55 465 ouverte le 22 août 2023

 (8 commentaires) (0 réaction) (0 personne assignée)TypeScript (13 395 forks)batch import
Experience EnhancementHelp WantedSuggestion

Métriques du dépôt

Stars
 (108 860 étoiles)
Métriques de merge PR
 (Métriques PR en attente)

Description

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

Guide contributeur