Search Terms:
I did ask here https://stackoverflow.com/questions/54593103/typescript-union-type-with-singleton-types-does-not-compile
Code
type X = {
id: "primary"
inverted?: boolean
} | {
id: "secondary"
inverted?: boolean
} | {
id: "tertiary"
inverted?: false
}
const a = true
const x: X = {
id: a ? "primary" : "secondary"
}
Expected behavior:
Compiles
Actual behavior:
禄 node_modules/typescript/bin/tsc test.ts
test.ts:14:7 - error TS2322: Type '{ id: "primary" | "secondary"; }' is not assignable to type 'X'.
Type '{ id: "primary" | "secondary"; }' is not assignable to type '{ id: "tertiary"; inverted?: false; }'.
Types of property 'id' are incompatible.
Type '"primary" | "secondary"' is not assignable to type '"tertiary"'.
Type '"primary"' is not assignable to type '"tertiary"'.
14 const x: X = {
~
Playground Link:
https://www.typescriptlang.org/play/#src=type%20X%20%3D%20%7B%0D%0A%20%20id%3A%20%22primary%22%0D%0A%20%20inverted%3F%3A%20boolean%0D%0A%7D%20%7C%20%7B%0D%0A%20%20id%3A%20%22secondary%22%0D%0A%20%20inverted%3F%3A%20boolean%0D%0A%7D%20%7C%20%7B%0D%0A%20%20id%3A%20%22tertiary%22%0D%0A%20%20inverted%3F%3A%20false%0D%0A%7D%0D%0A%0D%0A%0D%0Aconst%20a%20%3D%20true%0D%0Aconst%20x%3A%20X%20%3D%20%7B%0D%0A%20%20id%3A%20a%20%3F%20%22primary%22%20%3A%20%22secondary%22%0D%0A%7D
This is working as intended. In general we don't consider a type { x: A | B } assignable to { x: A } | { x: B }, even though in the rare case where all other properties have identical types we potentially could.
If this is working as intended (I don't think it should be) the error message could be improved. I read Type '"primary"' is not assignable to type '"tertiary" and thought to myself: I doesn't have to be assignable to "tertiary". I took me a while to figure out the error is not caused by something I did but something I assumed typescript would do. The object matches the type definition (in my head) and it still doesn't fit. So a better error message could help me and others to understand this without wasting time.
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.
Most helpful comment
If this is working as intended (I don't think it should be) the error message could be improved. I read
Type '"primary"' is not assignable to type '"tertiary"and thought to myself: I doesn't have to be assignable to "tertiary". I took me a while to figure out the error is not caused by something I did but something I assumed typescript would do. The object matches the type definition (in my head) and it still doesn't fit. So a better error message could help me and others to understand this without wasting time.