Generate a fresh class instance in Typescript by using an existing class instance as the base

If I have these two classes:

class MyTypeOne {
  constructor(
      public one = '',
      public two = '') {}
}

class MyTypeTwo extends MyTypeOne {
  constructor(
      one = '',
      two = '',
      public three = '') {
    super(one, two)
  }
}

What is the most efficient way to generate a new MyTypeTwo object based on an existing MyTypeOne object?

Answer №1

Implementing a mapping process is inevitable unless you want to manually iterate over object keys, which would make the code harder to read and longer. In such cases, utilizing creational patterning can be more efficient!

class MyTypeOne {
    constructor(
        public one = '',
        public two = '') { }
}

class MyTypeTwo extends MyTypeOne {
    constructor(
        one = '',
        two = '',
        public three = '') {
        super(one, two)
    }

    static fromMyTypeOne(myTypeOne: MyTypeOne) {
        return new MyTypeTwo(myTypeOne.one, myTypeOne.two);
    }
}

const one = new MyTypeOne('a', 'b');
const two = MyTypeTwo.fromMyTypeOne(one);

console.log(two);

Auto-Map

For thoroughness, here is an extended version that automatically maps the members. It offers a different set of trade-offs!

class MyTypeOne {
    constructor(
        public one = '',
        public two = '') { }
}

class MyTypeTwo extends MyTypeOne {
    constructor(
        one = '',
        two = '',
        public three = '') {
        super(one, two)
    }

    static fromMyTypeOne(myTypeOne: MyTypeOne) {
        const typeTwo = new MyTypeTwo();

        for (let key in myTypeOne) {
            if (myTypeOne.hasOwnProperty(key)) {
                typeTwo[key] = myTypeOne[key];
            }
        }

        return typeTwo;
    }
}

const one = new MyTypeOne('a', 'b');
const two = MyTypeTwo.fromMyTypeOne(one);

console.log(two);

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

How do I remove a specific object from my localStorage array in Angular?

Currently, I am storing and retrieving form values from localStorage. When displaying the data, I want to be able to remove a specific object that is clicked on. The issue is that my current code removes all the data instead of just the selected object. Be ...

The declared type 'never[]' cannot be assigned to type 'never'. This issue is identified as TS2322 when attempting to pass the value of ContextProvider using the createContext Hook

I'm encountering an issue trying to assign the state and setState to the value parameter of ContextProvider Here's the code snippet:- import React, { useState, createContext } from 'react'; import { makeStyles } from '@material-ui ...

I'm interested in learning how to implement dynamic routes in Nexy.js using TypeScript. How can I

I have a folder structure set up like this: https://i.stack.imgur.com/qhnaP.png [postId].ts import { useRouter } from 'next/router' const Post = () => { const router = useRouter() const { pid } = router.query return <p>Post: {p ...

What is the best approach for dynamically accessing or rendering Children within an Angular Component?

I am facing an issue with reusing a component called wrapper with different child components. I found some helpful resources such as this SO question and this article. However, these only address cases where the child component is known in advance. In my s ...

How can one use TypeScript to return a subclass instance within a static function of a base class?

Below is the code snippet: class BaseElement { public static create<T extends typeof BaseElement>(this: T ): InstanceType<T> { this.createHelper(); const r = new this(); return r; } public static createHelpe ...

When the typeof x is determined to be "string", it does not result in narrowing down to just a string, but rather to T & string

Could someone help me understand why type narrowing does not occur in this specific case, and return typing does not work without using: as NameOrId<T>; Is there a more efficient way to rewrite the given example? Here is the example for reference: ...

It takes a brief moment for CSS to fully load and render after a webpage has been loaded

For some reason, CSS is not rendering properly when I load a webpage that was created using React, Next.js, Material UI, and Styled-components. The website is not server-side rendered, but this issue seems similar to what's described here You can see ...

When utilizing a personalized Typescript Declaration File, encountering the error message 'Unable to resolve symbol (...)'

I'm having trouble creating a custom TypeScript declaration file for my JavaScript library. Here is a simplified version of the code: App.ts: /// <reference path="types.d.ts" /> MyMethods.doSomething() // error: Cannot resolve symbol "MyMetho ...

The specified type '{ rippleColor: any; }' cannot be assigned to type 'ColorValue | null | undefined'

I've been diving into learning reactnative (expo) with typescript, but I've hit a roadblock. TypeScript keeps showing me the error message Type '{ rippleColor: any; }' is not assignable to type 'ColorValue | null | undefined' ...

Create a function that will always output an array with the same number of elements as the input

Is there a method to generate a function that specifies "I accept an array of any type, and will return the same type with the same length"? interface FixedLengthArray<T, L extends number> extends Array<T> { length: L; } export function shuf ...

How do you obtain the string name of an unknown object type?

In my backend controllers, I have a common provider that I use extensively. It's structured like this: @Injectable() export class CommonMasterdataProvider<T> { private readonly route:string = '/api/'; constructor(private http ...

Angula 5 presents a glitch in its functionality where the on click events fail

I have successfully replicated a screenshot in HTML/CSS. You can view the screenshot here: https://i.stack.imgur.com/9ay9W.jpg To demonstrate the functionality of the screenshot, I created a fiddle. In this fiddle, clicking on the "items waiting" text wil ...

Streamline imports with Typescript

Is there a way to import modules with an alias? For example, I have an angular service in the folder common/services/logger/logger.ts. How can I make the import look like import {Logger} from "services" where "services" contains all my services? I've ...

In the latest version of Angular, accessing document.getelementbyid consistently returns null

I am struggling with a component that looks like this export class NotificationPostComponent extends PostComponent implements OnInit, AfterViewInit { commentsDto: IComment[] = []; commentId = ''; ngOnInit(): void { this.route.data ...

Does anybody have information on the Namespace 'global.Express' not having the 'Multer' member exported?

While attempting to set up an endpoint to send a zip file, I keep encountering the following error: ERROR in ./apps/api/src/app/ingestion/ingestion.controller.ts:46:35 TS2694: Namespace 'global.Express' has no exported member 'Multer'. ...

Typescript is throwing an error with code TS2571, indicating that the object is of type 'unknown'

Hey there, I'm reaching out for assistance in resolving a specific error that has cropped up. try{ } catch { let errMsg; if (error.code === 11000) { errMsg = Object.keys(error.keyValue)[0] + "Already exists"; } return res.status ...

Identifying collisions or contact between HTML elements with Angular 4

I've encountered an issue that I could use some help with. I am implementing CSS animations to move p elements horizontally inside a div at varying speeds. My goal is for them to change direction once they come into contact with each other. Any sugges ...

"Embracing the power of multiple inheritance with Types

I am struggling with the concept of multiple inheritance in TypeScript. It doesn't make sense to overload a hierarchy with too much functionality. I have a base class and several branches in the hierarchy. However, I need to utilize mixins to isolate ...

Match and populate objects from the array with corresponding items

Currently, I have an array and object containing items, and my goal is to check each item in the array to see if its path matches any of the object names. If a match is found, I push it into that object's array. While this part is working fine, I am ...

Difficulties with managing button events in a Vue project

Just getting started with Vue and I'm trying to set up a simple callback function for button clicks. The callback is working, but the name of the button that was clicked keeps showing as "undefined." Here's my HTML code: <button class="w ...