How can you typically verify the type of an object variable in TypeScript?

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!

Answer №1

interfaces in TypeScript are a static feature, while instanceof is a dynamic operator in ECMAScript. It's important to note that at runtime, interfaces do not exist and ECMAScript is unaware of TypeScript types.

Due to this limitation, checking if an object adheres to an interface at runtime is not possible.

To overcome this obstacle, consider using a validation library like zod. With zod, you can infer the TypeScript type of an 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 validation fails
    ItemSchemaArray.parse(items);
};

Konrad mentioned this library in the comments above.

Thank you, @Konrad!

Answer №2

To ensure that an object matches the requirements outlined in an interface, you can establish a type guard function. For instance:

function isPerson(obj: any): obj is Person { return obj && typeof obj.name === 'string' && typeof obj.age === 'number'; }
will evaluate to true or false based on whether the parameters meet the specified types. Subsequently, modify your console log to display console.log(isPerson(obj));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS: monitoring changes in an array property

For the problem at hand, take a look at this link: http://plnkr.co/edit/ZphAKvZeoVtuGFSEmOKg?p=preview Imagine you have an array structured like this: var arr = [ { 'a': "123", 'b': "654" }, { 'a': "456", &apo ...

Tips for adding an array to a formData: incorporating an array with two values along with their corresponding keys

Snippet : const options = new RequestOptions({ headers: headers }); let myArray; myArray = [{ "subfolder_name": subfolder, "file_upload": file }]; let formData: FormData = new FormData(); formData.append("folder_name",folder ); formData.append("counse ...

I am having trouble retrieving the properties of "2d" objects using tiles[i-1], unlike standard objects in JavaScript

I've been working on constructing a random map generator by utilizing a grid composed of tiles within a canvas. In my process, I'm investigating the properties of each tile tiles[i] before handling tiles[i-1]. While this procedure seems to functi ...

Revising HTML content when Angular array is modified

I have a code snippet below where I am updating the value of an object in the first item of an array. However, I'm struggling to find a way to "refresh" the HTML view so that the changes are immediately reflected on the browser. var dataArr ...

Is there a way to track when the Angular DTOptionsBuilder ajax call is complete and trigger a callback function?

Working with angular datatables, I have the following code: beforeSend:</p> success callback causes the table on the page not to populate with the data. How can I implement a callback that triggers once the ajax is done without interfering with the ...

"Send the response in ExpressJS before making a request to loop through the

I am currently working with a postgres database that contains records with a column format in JSON, which refers to other similar records. The challenge I am facing is retrieving linked records through asynchronous methods due to the nested structure and ...

Apologies, but there was an error attempting to differentiate 'nombreyo'. Please note that only arrays and iterables are permitted for this action

Encountering an error while attempting to display a class in the HTML. <li> <ul> <li *ngFor="let refac of refactormodel" > -- word_to_rename: {{refac.word_to_rename}} -- renowned_word: {{refac.renowned_word}} ...

Having trouble with Nextjs API Integration - encountering error 404

I'm currently facing a major issue and I've hit a dead end. I've been spending days trying to connect my local nextjs 14 app to the CVENT API, but I keep receiving a persistent 404 error. Here's what is displayed in the frontend console ...

The CSS transition fails to function correctly once a specific function is executed

When I hover over a div, the background color changes due to a transition effect. However, if I click on a button that triggers myFunction2 to change the background color of the div before hovering over it, the transition effect no longer works. functi ...

How can I defer Tween.js animation in three.js until a button is specifically clicked?

I am trying to implement a tween animation for my camera in three.js that should only start when a specific object is clicked. This object can be within the scene or it could be a simple HTML button. The code snippet below demonstrates how the camera anima ...

HTML and JavaScript code to desaturate or grayscale image rollovers without the need for additional image duplicates or sprites

Is there a way to achieve grayscale to color image rollover effects without duplicating images or using sprites? I'm looking for an alternative technique that can accomplish this. Any suggestions on how to implement it? ...

Error in TypeScript React: "Could not locate module: Unable to locate 'styled-components'"

Even though I have installed the @types/styled-components package and compiled my Typescript React app, I am consistently encountering this error: Module not found: Can't resolve 'styled-components' I have double-checked that 'style ...

Using async/await does not execute in the same manner as forEach loop

Here is a code snippet that I have been working with. It is set up to run 'one' and then 'two' in that specific order. The original code listed below is functioning correctly: (async () => { await runit('one').then(res ...

HTML5 enables the creation of an imperceptible scrollbar

I am looking to make my scrollbar invisible without it being visible however, I still want it to function when hovering over the box Also, I need it to work smoothly on both tablets and computers, which is why I have opted for using html5 I would great ...

Developing a system mode called "night mode"

I've decided to incorporate a dark mode feature into my Wordpress theme. Creating both dark and light modes was a breeze, but now I want to add a third mode that serves as the default for pages. This new mode will automatically switch between dark a ...

What is the best way to determine if a user is currently in a voice channel using discord.js?

Is there a way for me to determine if a user is currently linked to a voice channel? I am trying to implement a command that allows me to remove a user from a voice channel, and here is how I am attempting to check: const user: any = interaction.options.ge ...

Ways to retrieve the output from an AJAX call

Today I'm developing a JavaScript function named "sendData". This function simplifies the process by eliminating the need to manually code an entire ajax statement. However, considering that it operates asynchronously, I found myself wondering how to ...

The functionality of the delete button in Material UI Chip seems to be malfunctioning

I am working on mapping Material UI Chips, but I am facing an issue where the cross button is not showing up and I cannot click on them or use the onTouchTap event. Below is my mapping: {mapping.map(chipMap => { return ( <div> ...

Chrome Extension to Emphasize Every Word

As a novice, I am embarking on the journey of creating my own chrome extension. The idea is to design a popup.html file that showcases a "highlight" button. The functionality would involve clicking this button to highlight all words on the page. Here&apos ...

The React.js Mui Collapse component exclusively triggers animation during the transition while closing, without any animation when expanding

Whenever I implement the Collapse component from Mui library in my projects, I face an issue where the transition animation only works when closing the component (when in={false}). However, when opening the component, there is a delay before the animation ...