skip to Main Content

I want to check if the obj object variable has all the properties of the Person interface.

interface Person {
  name: string;
  age: number;
}

const jsonObj = `{
  name: "John Doe",
  age: 30,
}`;

const obj: Person = JSON.parse(jsonObj);

const isPerson = obj instanceof Person; // Person is not defined

console.log(isPerson); // true

When I execute this code, it yield Person in not defined!

I would expect the code to log true as the obj is an instance of Person.

2

Answers


  1. interfaces are a static TypeScript feature. instanceof is a dynamic ECMAScript operator. interfaces do not exist at runtime, and ECMAScript does not know anything about TypeScript types.

    Therefore, you cannot test at runtime whether an object conforms to an interface.

    Login or Signup to reply.
  2. You can create a type guard function that checks if the object adheres to the types set out in the interface. So:
    function isPerson(obj: any): obj is Person { return obj && typeof obj.name === 'string' && typeof obj.age === 'number'; }
    will return true or false if either of the parameters are not the types specified.
    You will then change your console log to console.log(isPerson(obj));

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search