I'm confused because I can't find a definite answer to this question:
Consider the following type definition:
type A = {
prop2: string;
prop1: string;
} | {
prop3: string;
prop1: string;
}
This type includes one shared property and two distinct properties. Surprisingly, I can instantiate it like this:
const a: A = {
prop1: '',
prop2: '',
prop3: '',
};
Surprisingly, no errors are thrown!
However, when I try to access prop2 and prop3, TypeScript only allows me to do so after performing additional checks:
a.prop1 = '';
// @ts-expect-error
a.prop2 = ''; // ERROR
if ('prop2' in a) {
a.prop2 = ''; // OK
}
My confusion lies in why TypeScript permits declaring both props even though it restricts their use in objects. When using this definition in a React component, all props could be passed freely.
Furthermore, I am restricted to using prop1, prop2, and prop3 only; I cannot include a prop4.