How can I verify if the obj variable contains all the properties defined in 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
Upon running this code, the error message Person in not defined
is displayed!
I expected the output to be true since the obj variable is an instance of Person.
-----
Answer Update: Different Functional Solution Using zod Library
TypeScript operates during compile-time only, while instanceof is a runtime concept. It cannot be used on a type as types are non-existent in JavaScript.
A possible solution is to utilize a validation library such as zod. By using zod, you can derive the TypeScript type of the object and validate it accordingly.
For instance,
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);
// The line below will throw an error if the validation fails
ItemSchemaArray.parse(items);
};
Konrad highlighted this library in the comments section below.
Thank you, @Konrad!