What is the best way to duplicate a Typescript class object while making changes to specific properties?

I have a Typescript cat class:

class Kitty {
  constructor(
    public name:  string,
    public age:   number,
    public color: string
  ) {}
}

const mittens = new Kitty('Mittens', 5, 'gray')

Now I want to create a clone of the instance, but update one property. If this were a plain object, it would be simple:

const whiskers = {...mittens, name: 'Whiskers'}

But that doesn't result in an instance of the Kitty class. To achieve that, I need to manually specify each property:

const Whiskers = new Kitty('Whiskers', mittens.age, mittens.color)

Is there a more efficient way to duplicate a class instance, rather than a plain object, while modifying specific properties?

Answer №1

A static factory method can be implemented to create a new instance based on the object provided

class Cat {
  constructor(...) {...}
  
  static fromObject({ name, age, color }) {
    return new Cat(name, age, color)
  }
}

To update the sophie object with a new name:

const tipper = Cat.fromObject({ ...sophie, name: "Tipper" })

class Cat {
  constructor(name, age, color) {
    this.name = name;
    this.age = age;
    this.color = color
  }
  
  static fromObject({ name, age, color }) {
    return new Cat(name, age, color)
  }
}

const sophie = new Cat('Sophie', 17, 'black')
const tipper = Cat.fromObject({ ...sophie, name: "Tipper" })

console.log(tipper)
console.log(tipper instanceof Cat)


Alternatively,

If you adjust the constructor signature, you can directly pass an object as an argument

class Cat {
  constructor({ name, age, color }) {
     ...
  }
}

new Cat({ ...sophie, name: "Tipper" })

class Cat {
  constructor({ name, age, color }) {
    this.name = name;
    this.age = age;
    this.color = color
  }
}

const sophie = new Cat({ name: "Sophie", age: 17, color: "black" })
const tipper = new Cat({ ...sophie, name: "Tipper" })

console.log(tipper)
console.log(tipper instanceof Cat)

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

Express Form Validation: Ensuring Data Accuracy

I have recently learned that client-side form validations may not be sufficient to prevent malicious actions from users. It is recommended to also validate the form on the server-side. Since I am new to using express, can someone provide guidance on what s ...

Vercel encountered issues with "validating code quality and type correctness" during deployment but was successful when performed locally

Running "next build" locally and "vercel build" both work smoothly. However, once deployed to vercel, the "Linting and checking validity of types" fails during the build process. It seems like TypeScript is stricter when building on vercel even with the sa ...

What type is the appropriate choice for this handler?

I´m struggling to select the right type for this particular function. It serves as an async handler for express js in a project that utilizes typescript and eslint for linting with specific rules. export function asyncHandler( handler: any ): (req: Requ ...

One efficient way to handle multiple concurrent tasks in NodeJs is by using the forEach method to iterate

Having trouble getting the promises to return any values, as they are coming back empty. Despite following suggestions on Stack Overflow, I am still unable to resolve this issue. Frustration levels are high and I'm feeling lost; Can anyone help me pi ...

The Problem of Unspecified Return Type in Vue 3 Functions Using Typescript

Here is the code snippet I am working with: <template> <div> <ul v-if="list.length !== 0"> {{ list }} </ul> </div> </template> < ...

Utilizing Rxjs to transform an array of objects

My goal is to map an array of objects. Currently, I have the following code: return this.service.post(url, payload, this.httpOptions) .pipe( map((obj: any, index) => [({ ...obj, val1: obj[index].val1.id, v ...

Using React for passing data

In the snippet found in "CameraPage.tsx", there is a logical function that is responsible for fetching camera images. This function simply makes a GET request to search for images stored in the backend, which will later be displayed on the FrontEnd. The op ...

Dealing with multipart/form-data in Express using cloud functions in the upcoming year of 2022

Seeking advice on handling multipart/form-data requests in an Express backend with Google Cloud Functions in 2022. Despite numerous attempts, the issue remains unresolved after extensive research and testing various methods that work locally but fail when ...

Tips for updating Okta token when there are changes to claims

Currently, my react app is successfully using oauth (specifically okta), but I am encountering a problem. Whenever I modify the claims in the authorization server, the changes are not reflected in the app until the token expires or I perform a logoff and ...

After introducing 5 guard properties, the intersection of unions in Typescript breaks down

In TypeScript, I am attempting to create a class where properties are only accessible if another property has been checked on the class. This needs to be done in a generic manner to facilitate reuse across multiple classes. For instance, class Test { Fo ...

Mastering the implementation of type refinements for io-ts in processing input data

I have implemented io-ts for defining my typescript types. This allows me to perform runtime type validation and generate type declarations from a single source. In this particular scenario, I aim to create an interface with a string member that needs to ...

Tips for improving the performance of MongoDB queries in a Node.js environment

I am currently facing an issue with my code running in nodejs where I need to call a MongoDB query with aggregation properties using callbacks. However, the code is not functioning as expected. I want the code to run asynchronously so that once the MongoDB ...

When using Javascript, the click function is returned as not being a valid function

I am working on a project with two PHP files - index.php and loadimages.php. The index.php page contains a thumbnail gallery and a canvas. The images in the thumbnail gallery are populated by loadimages.php. Here is a snippet of the code from loadimages.ph ...

Access to PHP script (IF) unattainable following a POST occurrence

I'm completely new at this. I am attempting to create a contact form using HTML5 and PHP mail function, but I am facing an issue with my form action pointing to contacto.php. After submitting the form, it seems to be skipping over the IF condition wi ...

When running the command "npx create-next-app@latest --ts," be aware that there are 3 high severity vulnerabilities present. One of the vulnerabilities is that "node-fetch

Just set up a fresh project with Next.js and TypeScript by following the documentation using npx create-next-app@latest --ts. Encountering multiple high severity vulnerabilities despite running npm audit fix --force, which actually adds more vulnerabiliti ...

Activate a particular panel within the leftPanel using PDFNet Webviewer

When using disableElements in the setQuickBarPanelContents() function, I am able to remove 2 of the 3 panels from the leftPanel: setQuickBarPanelContents() { this.instance.disableElements(['notesPanel', 'notesPanelButton', &apos ...

The disappearance of the checkbox is not occurring when the text three is moved before the input tag

When I move text three before the input tag, the checkbox does not disappear when clicked for the third time. However, if I keep text three after the input tag, it works fine. Do you have any suggestions on how to fix this issue? I have included my code be ...

Responding to a tweet with the help of twit and Node.js

Utilizing the Twit Node.js API has presented me with a challenge. I am attempting to reply to a tweet that contains a specific keyword. My goal is for my response tweet to appear nested underneath the original tweet, much like how replies function on socia ...

Issues with injection of angularjs, sockjs, and angular-sockjs are causing functionality to not

As a newcomer to technologies like angular, sockjs-client, and cyclone, I've encountered an injection issue while attempting to utilize a component created by bendrucker. The component in question can be found at this link: https://github.com/bendruck ...

unable to choose just one material ui checkbox

I'm new to using React and I'm currently developing a simple todo app with React JS and Material UI. To accomplish this, I've created two separate components - one for taking user input (TodoInput) and another for rendering each individual t ...