0

I have a type union composed of A | (A & B)

I need to check for a property that only belongs to B but typescript doesn't allow me to:

interface A {
  a: number;
  b: number;
  c: number;
}

type B = A & {
  d: number;
}

type Detail = A | B

declare const test: Detail

// Why can't I check for property d ?
if (test.d) {

}

If B is in the union why is this an error ?

Playground

nook
  • 1,729
  • 1
  • 12
  • 34
  • Because `test` might be an `A`, not an `A & B`. Use a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) or [`in`](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-in-operator-narrowing) to check whether `test` has `d` (e.g., is an `A & B`). – T.J. Crowder Oct 04 '22 at 09:58

0 Answers0