Microsoft/TypeScript

Incorrect error message on invalid union type assignation

Open

#55.465 aberto em 22 de ago. de 2023

Ver no GitHub
 (8 comments) (0 reactions) (0 assignees)TypeScript (6.726 forks)batch import
Experience EnhancementHelp WantedSuggestion

Métricas do repositório

Stars
 (48.455 stars)
Métricas de merge de PR
 (Mesclagem média 6d 17h) (9 fundiu PRs em 30d)

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.

Guia do colaborador