0

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.

 ----- 




Answer Update: Alternative Working Solution Using zod Library

TypeScript works only in compile-time, but instanceof is a runtime thing. You can't use on a type, because types doesn't exist in javascript.

You can use a validator library like zod. Then, you can infer the ("TypeScript") type of the object and validate it with zod.

Per example,

import { z } from 'zod'; export const ItemSchema = z.object({ name: z.string(), description: z.string(), productServiceId: z.number().optional(), }); export type Item = z.infer<typeof ItemSchema>; const validateItems = (items: Item[]) => { const ItemSchemaArray = z.array(ItemSchema); // This line below will throw an error if the validation failed ItemSchemaArray.parse(items); }; 

Konrad referenced this library in the comments below.

Thank you, @Konrad!

6
  • 3
    TypeScript works only in compile-time, but instanceof is a runtime thing. You can't use on a type, because types doesn't exist in javascript. You can use a validator like zod Commented Feb 20, 2024 at 10:46
  • See what your code is compiled to Commented Feb 20, 2024 at 10:50
  • Are you sure you want to use instanceof or is that an XY problem? Commented Feb 20, 2024 at 10:56
  • I understand. The reading of code writing in TypeScript code is quite different then compile TypeScript code. I will check the zod library. Commented Feb 20, 2024 at 10:57
  • 1
    @Konrad, I have updated my answer with a working solution based on the library, zod, you have proposed. - Thank you! Commented Mar 3, 2024 at 19:26

2 Answers 2

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.

You can use a validator library like zod. Then, you can infer the ("TypeScript") type of the object and validate it with zod.

Per example,

import { z } from 'zod'; export const ItemSchema = z.object({ name: z.string(), description: z.string(), productServiceId: z.number().optional(), }); export type Item = z.infer<typeof ItemSchema>; const validateItems = (items: Item[]) => { const ItemSchemaArray = z.array(ItemSchema); // This line below will throw an error if the validation failed ItemSchemaArray.parse(items); }; 

Konrad referenced this library in the comments above.

Thank you, @Konrad!

Sign up to request clarification or add additional context in comments.

2 Comments

I understand that reading TypeScript code is different from reading compiled TypeScript code. However, I think it would be great to have such an implementation of "instanceof" under the hood where the compiled TypeScript checks the existence of each key for the object.
Your proposal violates TypeScript Design Goals #3 and #9, and Non-Goals #5 and #6.
1

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));

2 Comments

This solution, contrary to be general, only applies to an object that implements / is a Person. I wanted a general solution as my interfaces are way more complex; my interfaces as many key-value pairs.
Apologies for the misread. But agree that it would be nice to have a under the hood implementation of instanceof in TS. Unfortunately, there is no general way to check from what I can see.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.