1

I'm trying to evaluate an object based on two types, without looking explicitly at its children, as a value could not exist (based on my use-case).

Let's say I have two interfaces with different properties.

interface A & interface B

How would I check an object is Type of A or Type of B?

I've tried the following:

interface A {
  foo: "value";
}

interface B {
  bar: "value";
}

const object = {
  bar: "value"
};

function isA(object: any): object is A {
  if (object as A) {
    return true;
  } else {
    return false;
  }
}

console.log(isA(object));

However, the result is always returned as True.

Codesandbox https://codesandbox.io/s/elastic-gagarin-01c7y?file=/src/index.ts:0-243

Xavier
  • 831
  • 3
  • 9
  • 22
  • Probably a duplicate: Does this answer your question? https://stackoverflow.com/questions/14425568/interface-type-check-with-typescript – Algef Almocera Jun 05 '20 at 19:11
  • @AlgefAlmocera I did check this originally but it's checking to see if a key is present on the type not actually what the type of the object. – Xavier Jun 05 '20 at 19:13
  • 3
    @XavierAkram a type does not exist in javascript, to which typescript compiles to, so the only way to check if an object is of a certain type is to check if it has a certain property which only belongs to that one interface – Poul Kruijt Jun 05 '20 at 19:16
  • Exactly as @PoulKruijt have said. – Algef Almocera Jun 05 '20 at 19:38
  • Thanks for clarifying, I wasn't aware of the intimate mechanics of typescript. +1 – Xavier Jun 05 '20 at 19:51

0 Answers0