What could be the reason for the failure of my class isInstance() check

Do you see any issues with the object being an instance of ChatRoom? Let me know your thoughts.

Class:

export class ChatRoom {
  public id?: number;
  public name_of_chat_room: string;
  public chat_creator_user_id: number;
  public chat_room_is_active: 0 | 1;
  public chat_room_is_shareable: 0 | 1;
  public time_of_most_recent_message?: Date | string;
  public created_at?: Date | string;

  constructor(chatRoom: {
    name_of_chat_room: string;
    chat_creator_user_id: number;
    chat_room_is_active: 0 | 1;
    chat_room_is_shareable: 0 | 1;
    time_of_most_recent_message?: Date | string;
  }) {
    Object.assign(this, chatRoom);
  }
}

finalResult object that is not working as expected:

{
    name_of_chat_room: 'First Posted Chat Room',
    chat_creator_user_id: 21,
    chat_room_is_active: 1,
    chat_room_is_shareable: 1
  }

if statement that needs attention:


if (finalResult instanceof ChatRoom){
console.log("hooray")
}else{
console.log("foooey")
}

Complete code snippet

export class ChatRoom {
  public id ? : number;
  public name_of_chat_room: string;
  public chat_creator_user_id: number;
  public chat_room_is_active: 0 | 1;
  public chat_room_is_shareable: 0 | 1;
  public time_of_most_recent_message ? : Date | string;
  public created_at ? : Date | string;

  constructor(chatRoom: {
    name_of_chat_room: string;
    chat_creator_user_id: number;
    chat_room_is_active: 0 | 1;
    chat_room_is_shareable: 0 | 1;
    time_of_most_recent_message ? : Date | string;
  }) {
    Object.assign(this, chatRoom);
  }
}

let finalResult = {
  name_of_chat_room: 'First Posted Chat Room',
  chat_creator_user_id: 21,
  chat_room_is_active: 1,
  chat_room_is_shareable: 1
}

if (finalResult instanceof ChatRoom) {
  console.log("hooray")
} else {
  console.log("foooey")
}

Answer №1

instanceof is not used to verify if an object possesses the same properties as a Class definition, but rather to determine if the object was initialized with that constructor (or a constructor that inherits from it).

For example:

var finalResult = new ChatRoom({
  name_of_chat_room: 'First Posted Chat Room',
  chat_creator_user_id: 21,
  chat_room_is_active: 1,
  chat_room_is_shareable: 1
});
finalResult instanceof ChatRoom

This should result in returning true.

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

Is it possible to showcase a variety of values in mat-select?

Is it possible to pass different values to the .ts file in each function? For example, can I emit a String with (selectionChange)="onChangeLogr($event)" and an object with (onSelectionChange)="onChangeLogr_($event)"? How would I go about doing this? ...

React Weather App: difficulties entering specific latitude and longitude for API requests

I have successfully developed an app that displays the eight-day weather forecast for Los Angeles. My next objective is to modify the longitude and latitude in the API request. To achieve this, I added two input fields where users can enter long/lat values ...

Balanced arrangement of components

As I work on my first electron app, I've created the initial layout. My goal is to have elements resize when the user adjusts the window size: The red part should change in both width and height The blue part should only adjust in height, not width ...

Having trouble accessing array elements in react components

When retrieving JSON data for a single student from the server in my React application, I am able to access this.state.info.Firstname but encountering difficulty accessing this.state.info.Father.Firstname. How can I access this information? This is my Rea ...

javascript to retrieve data by reducing

Here is the code snippet I am working with: var points = 4; var yModifier = []; for (var i = 0; i <= points; i++) { yModifier.push([]); }; yModifier.forEach( (a, j) => { var start = j; var end = start + points; fo ...

Ways of accessing an array within an if statement

I have a dashboard with admin privileges for my application. In this dashboard, the admin can select a user from a dropdown list. Once a user is selected, I make an AJAX call to retrieve the user's data and store it in a variable named $result. Howeve ...

Verify if the specified key is present in the type parameter and if it corresponds to the expected data type in the value parameter

I have a specific goal in mind: export interface GCLPluginConfig { [key: string]: string | number | boolean | Date | string[]; } export interface CorePluginConfig extends GCLPluginConfig { "core.lastUpdateCheck": Date; } export interface An ...

JavaScript debugging causing system freeze

Currently, I am working on a project that involves using MVC and dropdown lists. My issue arises when the dropdown list changes, as there is some javascript code that needs to execute. To troubleshoot the problem of the system locking up every time I tried ...

Utilize a pre-defined layout in a Vue component that is sent as a property

As a complete beginner, I kindly ask for your patience as I navigate through the coding basics. I am looking to utilize a template specified in the prop. The template is located within the DOM. My intention for approaching it this way is to reuse the comp ...

Implementing the SendOwl License API for theme licensing

Currently developing a Shopify theme for sale and exploring licensing options Considering using SendOwl's API for licenses - Shopify themes support html/css/js/liquid, no server-side code, so JavaScript is required. Can the SendOwl API be used to v ...

What allows the type expression to be considered valid with a reduced amount of arguments?

Currently diving into Typescript and focusing on functions in this unit. Check out the following code snippet: type FunctionTypeForArrMap = (value: number, index: number, arr: number[]) => number function map (arr: number[], cb: FunctionTypeForArr ...

Typescript classes implementing data hydration and dehydration techniques

Exploring ways to share TypeScript classes or interfaces between a React + TS frontend and node + TS backend. Converting class instances into JSON poses a challenge as TS types are removed during compile time. Considering options for defining objects in a ...

Loop through each JSON object and insert it into an HTML element

I am working on looping through a JSON object and converting it into HTML. While I can iterate through all the objects in the JSON, I am having trouble extracting just the first object. var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback ...

I'm having trouble understanding how to use JQuery's .live and .remove methods together

Check out this working jsfiddle, except for the function I'm troubleshooting. I am working on code that appends a table to a form when the value changes in the quantity field. I have two goals: Allow only one extra line at a time. Remove the extra ...

Utilizing $.getJSON to initiate a selection change event

I'm currently working on implementing a feature that involves adding categories to a dropdown list using jQuery Ajax. The goal is to load subcategories when a particular option is selected. However, I've encountered an issue where the addition o ...

What is the best way to automate sending emails for every error that arises in Node.js?

In the scenario where my node.js application is up and running, I am looking for a way to handle all types of errors (not just web errors) and have a function that can send an email notification when an error occurs. Essentially, before the error gets wr ...

Exploring PHP cURL with the power of jQuery

function php_download($Url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $Url); curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm"); curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0"); curl_setopt($ch, CURLOPT_H ...

creating an interactive table with the help of the useState hook

I'm new to JavaScipt and ReactJS, so I have a question that may seem obvious but I can't seem to figure it out. I am attempting to display my array in a table using useState, but currently I can only show the header. Additionally, if anyone know ...

What is the best way to choose two <li> elements with multiple classes in my WordPress navigation menu?

I am looking for a JavaScript function that will add the class "current_highlight" when an element with the class "activo2" also has the class "active". Here is my HTML code: <div class="navbar-header"> <button type="button " class="navbar-to ...

What is the best way to save the properties of elements in an array of objects within another array?

I have obtained attributes from objects within an array that I need to store in another array. Here is the data I am working with: My goal is to extract the `displays` name attribute and save it in the `opt[]` array, which would result in something like t ...