In my TypeScript project, I encountered a situation that could be simplified as follows:
Let's take a look at the type Type
:
type Type = {
a: number;
} | {
a: number;
b: number;
} | {
a: number;
b: number;
c: number;
};
I proceed to define the constant t
based on the Type
type:
const t: Type = {
a: 1,
c: 3
};
Surprisingly, this does not throw any error! Despite the restrictions set by the Type
definition, I was able to create an object with properties a
and c
. How is this possible?
Furthermore, when trying to access the c
property:
console.log(t.c);
A transpilation error occurs stating:
Property 'c' does not exist on type 'Type'. Property 'c' does not exist on type '{ a: number; }'.
This has left me puzzled and confused. What could be causing this unexpected behavior?