0

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)

ste
  • 3,087
  • 5
  • 38
  • 73
  • You can use a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) (as in [this answer](https://stackoverflow.com/a/40718205/157247) to the linked question) when you need to check *whether* an instance is one type or the other, or a [type assertion function](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions) if **you** know it's type A but TypeScript doesn't. [Here's your playground updated to use a type predicate](https://tsplay.dev/wORdRW). – T.J. Crowder Sep 07 '22 at 07:00

1 Answers1

-1

Try if condition. For typescript isTypeA is just a boolean, doesn't infer the type in the next line.

Amit Kumar
  • 620
  • 4
  • 17