Starting a typescript class with an already existing object - a step-by-step guide

Although my question may seem similar to previous ones, I have not found the answer I am looking for, so I am posting it here. Here is my example:

Class A{
  id:number;
  name:string;
}

Class B{
  id:number;
  name:string;
  age:number;
  grade:number;
}

const b = new B {id:1, name:'John', age: 20, grade: 10}

Now, I am trying to create a new instance of class A using only two attributes from class B. I want to achieve something like this:

const a = b as A;

The desired result should look like this:

a = {id:1, name:'John'}

Thank you for your help.

Answer №1

Code Snippet

class A {
  id: number;
  name: string;

  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
  }

  static toA<T extends { id: number, name: string }>({ id, name }: T): A {
    const newObject = new A(id, name);
    return newObject;
  } 
}

Explanation

Attempting to alter the runtime structure through clever TypeScript hacks is fruitless. Using as simply instructs TypeScript to consider b as an instance of A, without actually converting it to one. TypeScript will only enforce type-checking rules based on this assumption during compilation.

To truly convert an object, a explicit converter function must be implemented. This function takes an object with the necessary fields and constructs a new instance of class A with those fields.

Examples

class A {
  id: number;
  name: string;

  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
  }

  static toA<T extends { id: number, name: string }>({ id, name }: T): A {
    const newObject = new A(id, name);
    return newObject;
  } 
}

class B extends A {
  test: number;

  constructor(id: number, name: string, test: number) {
    super(id, name);
    this.test = test;
  }
}

const b = new B(1, "hi", 2);
console.log(A.toA(b)); // A { id: 1, name: 'hi' }

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

What are the steps for generating a diagram using Chart.js?

I'm attempting to use Chart.js to create a specific diagram. Current Challenges: The point on the x-axis should be centered within the categories. I would like the value to appear above the point. https://i.sstatic.net/FFFr1.png This is what my co ...

Formatting dates with HandlebarsJS

Dealing with a JSON file that contains multiple items each with different concert dates can be tricky. For example, one item may have the date value: date: "2014-11-27" In my HandlebarsJS template, I currently display the date like this: <p>{{dat ...

After upgrading to the latest version of .NET Core, the JSON body is no longer able to dynamically convert from a string

Initially, the .Netcore version was 2.2 where the string in JSON http request body could be converted to an integer in an object as shown below: Post: api/ValidateMember Host: XXXX Content-Type: application/json { "id": "125324" } This conversion work ...

Is there a way to halt the compiler until an Ajax request is fully processed?

Within my form, there is a field labeled parent keywords as a secret key. The validation of this form using JavaScript functions smoothly. It is designed to check if the secret key is associated with any parent or not. If not, the value is set to 0 by defa ...

Issues encountered when setting up a Context Provider in React using TypeScript

I am currently in the process of setting up a Cart context in my React TypeScript project, inspired by the implementation found here: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js. I'm encountering some conf ...

Is there a way to efficiently parse and categorize erroneous JSON data in JavaScript?

Resolved my issue var allKeys = ["key","en","ar"]; for(var i=0;i<allKeys.length;i++) { for(j=0;j<jsonText.Sheet1.length;j++) { console.log(allKeys[i] + ' - ' + jsonText.Sheet1[j][allKeys[i]]); } } Live demonstration Appreciation ...

"Although both jQuery and PHP are capable of setting the element attribute, it is only PHP that functions successfully

I have been trying to set an element attribute to adjust the range of a slider. Initially, I used ajax to fetch data from a php file and assign it to the attribute. The slider looked good with the value but unfortunately, it wasn't functioning as expe ...

Supply context to node package

I've encountered an issue with the code below, where sometimes the content is not passed correctly: var app = require('buildersApps'); app.addContent({ folderPath: __dirname + '/content/' }); app.start(); To address thi ...

exploring XML documents

With around 250,000 XML files, each named with a UUID, I am looking for the most effective way to perform a full text search on these files and identify the UUID of the matching ones. What would be the optimal approach for indexing them in a nodejs environ ...

Encountering difficulty when determining the total cost in the shopping cart

I am currently working on a basic shopping cart application and I am facing an issue when users add multiple quantities of the same product. The total is not being calculated correctly. Here is my current logic: Data structure for Products, product = { ...

Can we extract unique values from a JSONObject in Java?

I have a JSON file containing 500,000 objects in the following format: "WORKORDER": [ { "Attributes": { "SITEID": { "content": "BEDFORD" }, " ...

My string is being cut off due to the HTML value

My webpage utilizes HTML5 to enable file uploads directly from the browser. The uploaded file is a PDF that needs to be displayed within an <input type="text"/> The following is my code snippet: var files = evt.target.files; // FileList object // ...

What is the proper method for transforming an Excel column containing JSON format data into a JavaScript object?

I am facing an issue with converting data from an excel sheet to json format. While the other columns convert successfully, one specific column containing json data is not being converted properly and instead gets treated as a string. Using JSON.parse() on ...

Adding reactions to a Discord webhook payload can enhance engagement and interaction within your server

section, I have encountered a dilemma. Despite my experience in creating webhook payloads for my discord servers, I have struggled to successfully add reactions to them. My go-to reference has been this documentation: . In my quest for answers, I have sco ...

Filtering the inner ng-repeat based on the variable of the outer ng-repeat

I have a collection of elements. Some of these elements are considered "children" of other elements known as "parent" elements. Instead of rearranging the JSON data received from the server, I am attempting to filter the results within the ng-repeat loop. ...

What setting should I adjust in order to modify the color in question?

Looking to Customize Radar Chart Highlighted Line Colors https://i.sstatic.net/PqWc4.png I am currently working on a Radar Chart and I am trying to figure out which property needs to be edited in order to change the color of the highlighted lines. I have ...

Locate the nearest span element and update its CSS class

On my page, there is a section with the following code: <h5 class="text-center" id="findStore" style="width:260px"> <a data-toggle="collapse" data-parent="#accordion" href="#@item.ProductId" aria-expanded="true" aria-controls="@item.ProductId ...

Steps for displaying detailed information about a single product on an Ecommerce page

Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...

How to invoke a custom JavaScript function within an ejs template

In an ejs file, I included my own JavaScript function which I intended to use within that file. However, the function is not working as it is declared as undefined. Below is how I declared the function inside the ejs file: //my ejs file <script> ...

Unlock the power of Angular JS to display dynamic content effortlessly

My experience with AngularJs is very limited. In one of my projects, I need to display dynamic content on a page that changes based on the database values retrieved via an HTTP GET request. Before implementing the entire functionality, I decided to test i ...