uioporqwerty
uioporqwerty

Reputation: 1158

How to compare two interfaces with Typescript?

If I have the following interfaces:

interface A {
  propA: string;
  propB: string;
}

interface B extends A {
  propC: string;
}

And I have another property such as:

interface Props {
  x: A | B
}

How can I check if x is of interface type A or B? Would I need to do a deep compare in this case since these aren't classes?

I was looking into a couple different methods like user defined type guards, or maybe using union types, but no dice.

Upvotes: 3

Views: 4752

Answers (1)

Dmitriy
Dmitriy

Reputation: 2822

In the union type as long as you can find a discriminator (something that has a specific type or only present in one of the types inside the union), you can use it inside a type guard:

interface A {
  propA: string;
  propB: string;
}

interface B extends A {
  propC: string;
  propD: string;
}

interface Props {
  x: A | B
}

const props: Props = {
  x: null as any
}

if ('propC' in props.x) {
  // TypeScript here assumes it is B 
  console.log(props.x.propC) // works
  console.log(props.x.propD) // also works
} else {
  // TypeScript here assumes it is A 
  console.log(props.x.propC) // error
  console.log(props.x.propD) // also error
  console.log(props.x.propA) // works
}

Upvotes: 2

Related Questions