Microsoft/TypeScript
在 GitHub 查看Incorrect error message on invalid union type assignation
Open
#55,465 创建于 2023年8月22日
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
💻 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.