I'm struggling to grasp the concept of unions in TypeScript. Can someone explain why the following assignment is considered valid? I believed it would only be acceptable for const a = {a:12}
, {a:123,b:23}
, or {a:12,b:12,c:123}
.
type abcd =
| {
a: number;
}
| {
a: number;
b: number;
}
| {
a: number;
b: number;
c: number;
};
const a: abcd = {
a:123,
c:234
};
If I change c
to somethingElse
, the assignment is not permitted:
const a: abcd = {
a:123,
somethingElse:234 // Error on this line
};
An error message stating:
Type '{ a: number; somethingElse: number; }' is not assignable to type 'abcd'. Object literal may only specify known properties, and 'somethingElse' does not exist in type 'abcd'.(2322)