in my TS project I have an object that can be of multiple types:
type ExampleInnerTypeA = {
c: "typeA";
d: string;
}
type ExampleInnerTypeB = {
c: "typeB";
e: string;
}
type ExampleType = {
a: string,
b: ExampleInnerTypeA | ExampleInnerTypeB;
}
When I instantiate the object with something like that:
const example: ExampleType = {
a: 'hello',
b: {c: "typeA", d: "hello world"},
}
I know I can make assumption on the properties of the object thanks to the parameter example.b.c
. In that string is equal to "typeA" I know the other existing property is d
, if that string is equal to "typeB" the other existing property is e
.
Nontheless when I perform checks like this:
const isTypeA = a.b.c == 'typeA'
const result = isTypeA ? a.b.d : a.b.e
I still get an error saying "Property 'd' does not exist on type 'ExampleInnerTypeA | ExampleInnerTypeB'." and "Property 'e' does not exist on type 'ExampleInnerTypeA | ExampleInnerTypeB'.", even though after the line:
const isTypeA = a.b.c == 'typeA'
I know exactly what type the object is. How can I make a check that will determine the correct type?
(link to to ts playground)