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

Preventing the detection of a jshint "error"

When creating an object using the constructor X, I later add multiple methods in the file using X.prototype.method = function () {...}. Although technically an assignment statement, it behaves like a function declaration, which typically doesn't requi ...

Resolving "SyntaxError: Unexpected identifier" when using Enzyme with configurations in jest.setup.js

I'm currently facing an issue while trying to create tests in Typescript using Jest and Enzyme. The problem arises with a SyntaxError being thrown: FAIL src/_components/Button/__tests__/Button.spec.tsx ● Test suite failed to run /Users/mika ...

What are the steps to resolving an issue with importing a css file in next.js?

Error: ./node_modules/quill-emoji/dist/quill-emoji.css ModuleParseError: Module parse failed: Unexpected character '�' (1:0) You may need a suitable loader for handling this file type, as there are currently no configured loaders to process it. ...

What is the process for inserting a new item into a mongoose array?

I'm currently developing a confidential web application. Below is the layout I've created for the user. const itemsSchema = { name: String } const userSchema = new mongoose.Schema({ username: String, email: String, password: String, M ...

Building a Laravel PHP application that dynamically generates a custom JSON object fetched from the database and passes it from PHP to

I am faced with the task of generating a custom JSON object by organizing data retrieved from PHP in my Controller. I have full control over what information goes where and in what specific order. To accomplish this, it seems like I will need to go throug ...

JavaScript for_each loop

Is there a way to access the field index of a JSON-Array when looping through it? I am aware that there is no foreach-loop like in PHP. This is an example of my json: { 'username': 'Karl', 'email': '<a href=" ...

Tips for addressing the error "Ensure each child in a list has a distinctive 'key' prop" in a React function using TypeScript

Encountered the following warning: Warning: Each child in a list should have a unique "key" prop. Inspect the render method of TabContext. Refer to https://reactjs.org/link/warning-keys for more details. in TabForGroupInList (at Product.tsx:148) ...

Activate Input by Clicking on Label in Internet Explorer version 8

I am trying to implement a widget in JQuery colorbox that allows users to load files. My approach involves using an input tag with type='file' and styling it with visibility:hidden. Additionally, I have created two labels that are styled like but ...

What are the steps to determine if a radio has been examined through programming?

In my form page, users can input an ID to fetch profile data from a MySQL database using AJAX. The retrieved data is then displayed in the form for editing. One part of the form consists of radio buttons to select a year level (e.g., "1", "2", "3", etc). ...

Guidance on implementing fallback font formats using FontFace API

I am exploring the FontFace API (not @fontface) and wondering if there is an easy way to include multiple font formats, similar to providing multiple sources in @fontface. Alternatively, is there a simple method to identify which font formats are supporte ...

What could be causing the error that pops up every time I attempt to execute a git push

When I executed the following command in git git push origin <the-name-of-my-branch> I encountered the following warning message Warning: The no-use-before-declare rule is deprecated since TypeScript 2.9. Please utilize the built-in compiler check ...

Im testing the creation of a global style using styled-components

Is there a way to create snapshot tests for styled-components with createGlobalStyle? The testing environment includes jest v22.4.4, styled-components v4.1.2, react v16.7, jest-styled-components v5.0.1, and react-test-renderer v16.6.3 Currently, the outp ...

Using Styled Components to Implement Background Images in a React Application

I'm currently attempting to pass a background image using a prop, but I'm encountering an issue where it's indicating that url is undefined. const CardImage = styled.div` height: auto; width: 100%; background-size: c ...

What method would you recommend for modifying HTML text that has already been loaded using JSP?

Is there a way to update text on an HTML document without reloading the entire page? I'm looking to create a simple "cart" functionality with 5 links on a page. When a link is clicked, I want it to increment the "items in cart" counter displayed on th ...

Submitting a form and obtaining results without relying on jQuery

Finding information on how to accomplish this task without using jQuery has proven to be a challenge. It seems like everyone is pushing for jQuery for even the simplest tasks nowadays. Despite avoiding unnecessary use of jQuery in creating a rich experienc ...

Looking for a way to add interactivity to this canvas rectangle?

ctx.fillStyle = "#9b958c"; ctx.fillRect(sampleRectX, sampleRectY, sampleRectW, sampleRectH); ctx.fillStyle = "#fff"; ctx.fillText("Click here to play again.", sampleTextX, sampleTextY); This clickable rectangle has been giving me some trouble. While I fou ...

Is it possible to display a combination of images and text data using JQUERY/AJAX, when the data is sent as objects or arrays?

I'm struggling to figure out how to handle an object or array sent from a server that contains binary picture and text data using JQUERY/AJAX Here is the server-side setup: const url= require('url'), express = require('express&ap ...

The @Input() function is failing to display or fetch the latest value that was passed

I am currently working on an angular project, and I've encountered a situation where I'm attempting to send a value from a parent component to a child component using the @Input() decorator. Despite my efforts, the child component continues to di ...

The Javascript function is being called, yet it cannot be defined

I am currently in the process of revamping an older website that was originally designed for compatibility with IE8 and utilizes framesets for layout management. As part of this update, I am trying to implement a piece of code within one frame that will g ...

The display/block feature will only function if the div element is contained within a table

I am facing an issue with hiding/showing two div elements alternatively. The code works perfectly when the divs are placed within a table, but fails when they are not in a table due to compatibility issues with Internet Explorer. I prefer not to use a tabl ...