Using the spread operator in Typescript with an object that contains methods

Within my Angular project, I am faced with an object that includes a type and status field where the status can change depending on the type. While some might argue that this is not the best design practice, it is how things are currently structured in my project. The issue I am encountering is that I am unable to utilize the spread operator on this object due to the compiler displaying an error message stating

Property 'getStatusList' is missing in type ...
.

To simplify, the class structure is similar to the following:

export class Foo {
    constructor(
        public type: number,
        public status: number
    ) { }

    getStatusList(): string[] {
        switch (this.type) {
            case 3: {
                return ['Off', 'Interval', 'On Hold']
            }
            default: {
                return ['Off', 'On']
            }
        }
    }
}

This situation arises with TypeScript version 2.9.2 and angular cli version 6.1.1

The code snippet below triggers the aforementioned error. However, while experimenting with sample code in TypeScript Playground, I realized that perhaps using Object.assign could be a solution. Yet, I initially believed that I could easily modify certain properties of an object using the spread operator.

const oldFoo: Foo = new Foo(3, 5);
console.log('old status: ', oldFoo.status);

const newFoo: Foo = { ...oldFoo, type: 1, status: 7 };
console.log('new status: ', newFoo.status);

Answer №1

Utilizing the spread operator in object literals will result in a new object that does not belong to the same class as the original. As stated in the documentation:

The spread operator copies own enumerable properties from a provided object onto a new object.

Through a shorter syntax than Object.assign(), shallow-cloning (excluding prototype) or merging of objects is now possible.

Therefore, you are merely "shallow-cloning" oldFoo. Any methods on the prototype will not be included. For an actual Foo object, it's advisable to construct one properly. Once constructed, you can use Object.assign() for setting multiple properties simultaneously. However, if you're already using a constructor, it's best to initialize with the correct parameters from the start.


It is potential to copy the prototype instead:

const newFoo = { ...oldFoo, type: 1, status: 7 } as Foo;
Object.setPrototypeOf(newFoo, Object.getPrototypeOf(oldFoo));

While this method may work, manipulating prototypes should be approached cautiously.


I hope this information proves helpful. Best of luck!

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

A guide to populating a Dropdown List in Angular2 with data from a JSON response

I am facing an issue where the data I receive from my web server is showing up as undefined when trying to bind it into my front-end application. The array seems to be populated with the correct number of objects, and the data is binding to the component b ...

The value of the filename property cannot be determined as it is undefined

Hey everyone, I'm currently working on a project using nestjs and reactjs. I encountered an error when trying to add a document that reads: "Cannot read properties of undefined (reading 'filename') in multer.config.ts" import { diskStorag ...

methods for displaying canvas in Angular 4

I recently began working with Angular4 and ng2 chart. My goal is to display text in the center of a doughnut chart within the canvas. While I am new to Angular4 canvas, I have been trying to achieve this but without success so far. Below is the setup in m ...

Rendering a React/Material UI class based on the state variable in a conditional manner

I am currently working on building a basic navbar setup using React and Material UI. I have encountered an issue where React-Router-Dom does not seem to be functioning within this particular project, and implementing it would be excessive for the simple ta ...

Is it possible to initiate the onchange event in Angular programmatically using Typescript?

Despite changing the value of an input tag after returning a value from a dialog box (MatDialogRef), the associated change event fails to trigger. Attempts to use dispatchEvent have been made, but creating the event for triggering is not desired as per fo ...

403 Error: Access Denied for Spring Cloud Gateway

Scenario In the development of my project, I have opted for a MicroServices architecture. Specifically, I am utilizing Angular 15 for the Frontend and Spring 3.0.2 as the Backend technology. To manage authentication for both the frontend and backend, I ha ...

Tips for adjusting column sizes in ag-grid

I'm a beginner with ag-grid and need some help. In the screenshot provided, I have 4 columns initially. However, once I remove column 3 (test3), there is empty space on the right indicating that a column is missing. How can I make sure that when a col ...

Is it possible to assign a variable to an Ionic datetime input property?

I am trying to pass a variable, someVar, into the max attribute (input property) of an Ionic 2 (and Angular 2) DateTime component. It seems like it only accepts a hardcoded string such as max="2017-08-31". HTML <ion-datetime displayFormat="DD/MM/YYYY" ...

Is it feasible to define a custom Type in Typescript that accurately represents a Treeview structure?

Typescript is a TYPED superset of JavaScript that compiles into JavaScript, fine! It helps us to reduce some typos etc. I want to create an interface that will serve as an argument in a method. This interface needs to represent a treeview for parsing an ob ...

TypeScript causing issues when multiple selectors are used

Currently, I have a function that allows me to search for HTML elements based on text content: function findElementsByText(text: string): HTMLElement[] { const selectors = 'button' // This conditional statement ensures that an empty text quer ...

The file isn't located in 'rootDir', even though all the details seem to be accurate

I'm currently troubleshooting an issue with one package in my nx monorepo that is causing the error code "TS6059". Interestingly, all other packages are functioning correctly in previous builds. After reviewing my index.ts files, it appears that all ...

What is a more organized approach to creating different versions of a data type in Typescript?

In order to have different variations of content types with subtypes (such as text, photo, etc.), all sharing common properties like id, senderId, messageType, and contentData, I am considering the following approach: The messageType will remain fixed f ...

Tsyringe - Utilizing Dependency Injection with Multiple Constructors

Hey there, how's everyone doing today? I'm venturing into something new and different, stepping slightly away from the usual concept but aiming to accomplish my goal in a more refined manner. Currently, I am utilizing a repository pattern and l ...

Encountering difficulties resolving the dependency tree for an angular-ionic project

Node version: v16.3.0 ng version: 12.1.0 Currently working on an Angular-Ionic 5 project Encountered an error while running the npm install command 2. Also tried running npm install --force but faced a different error ...

Encountered a problem while attempting to post in Angular, receiving an error message stating "net::ERR

I recently started learning Nodejs. I've created an API on a local server using Mysql and I'm working on the frontend with Angular, while using Nodejs and Express as the backend. However, I'm facing an issue where my Angular app cannot conne ...

How to extract the first initials from a full name using Angular TypeScript and *ngFor

I am new to Angular and still learning about its functionalities. Currently, I am developing an Angular app where I need to display a list of people. In case there is no picture available for a person, I want to show the first letters of their first name a ...

The ngModel in Angular 6 did not update the value within the app component

Currently, I am honing my skills in Angular and TypeScript but have encountered a minor issue. Below is the code snippet from my component.html <div> <input [(ngModel)]="mynumber"> N is now {{N}} // some content I want to do with ...

Problem: Unable to locate the TypeScript declaration file

I am facing an issue with my TypeScript configuration. I have two files in /src/models/: User.ts and User.d.ts. In User.ts, I am building a class and trying to use an interface declaration for an object defined in User.d.ts. However, User.ts is unable to a ...

The React hook useState is struggling to accurately map array objects

Recently, I encountered an issue with a form that sends an array of objects to another React Functional Component: import React, { useState } from 'react' import uuid from 'uuid/v1'; const NewMovieForm = ( {addMovie }) => ...

Enigmatic Cartography Classification

In my attempt to construct a specialized Map-like class that maps keys of one type to keys of another, I encountered a challenge. A straightforward approach would be to create a Map<keyof A, keyof B>, but this method does not verify if the member typ ...