Is there a way in TypeScript to automatically assign object properties to a class in an efficient manner?

Imagine a scenario where I have a unique class structured like this:

class Organization {

    title: string;
    website: string;
    location: string

    constructor() {
    }

}

Now, picture retrieving an object from a database that is known to contain some or all of the properties of my class, such as:

{title: "Tech Corp", website: "www.techcorp.com"}

Is there a method available for automatically building my class from this object?

Currently, one possible solution involves manually assigning values like so:

    const organization = new Organization();
    const obj = {title: "Tech Corp", website: "www.techcorp.com"}; // typically fetched from a database
    for (const key in obj) {
        if (key == "title") {
            organization.title = obj[key];
        }
        if (key == "website") {
            organization.website = obj[key];
        }

    }

However, this approach lacks elegance and can become cumbersome when dealing with numerous object properties.

Are there any automated techniques designed for this task?

Answer №1

Adapting my method:

const business = new Business();
const data = { name: "XYZ Corp", website: "www.xyzcorp.com" };

let approvedKeys: Array<keyof Business> = [
    'name','location','website'
];

for (const property in data) {
    if (approvedKeys.indexOf(property as keyof Business) !== -1) {
        business[property] = data[property];   
    }
}

The use of 'keyof Business' serves as a safety measure to ensure that only valid keys are added to the approvedKeys array.

I still believe there may be a more elegant solution, perhaps a better way to write the if-statement.

To resolve the compiler-error related to noImplicitAny, you can implement this approach (though I sense there might be room for improvement):

class Business implements KeySignature { 
    [key: string]: any;
    ...
 }

interface KeySignature {
    [key: string]: any;
}

const data = {
     name: "XYZ Corp", website: "www.xyzcorp.com"
} as KeySignature;

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

Exploring alternative applications of defineModel in Vue 3.4 beyond just handling inputs

The examples provided for defineModel in the Vue documentation primarily focus on data inputs. I was curious if this functionality could be utilized in different contexts, potentially eliminating the need for the somewhat cumbersome props/emit approach to ...

Angular HTTP Patch method requires explicitly defined HTTP options as input parameters

I encountered a challenge with using Angular's HTTP patch method and noticed that the overloaded function patch(url, body, options) only accepts hardcoded values for HTTP options. An example of a hardcoded approach that works: patchEntity(id: number) ...

Exploring the process of selecting checkboxes in Angular 6

I'm currently learning Angular 6 and I have a requirement to mark checkboxes based on specific IDs from two arrays: this.skillArray = [ {ID: 1, name: "Diving"}, {ID: 2, name: "Firefighting"}, {ID: 3, name: "Treatment"}, ...

Passing headers using a universal method in HTTP CRUD process

My service function is structured like this: Please note: I am required to work with cookies book(data: Spa): Observable<any> { return this.http.post(`${environment.apiURL}:${environment.port}/${environment.domain}/abc/my.json`, data, { ...

The functionality of Angular's mat-autocomplete is hindered when it comes to utilizing options generated by a function

I decided to enhance the autocomplete feature on my project by taking an example from the Material official website. Instead of having the options stored in a variable within the component class, I created a function to retrieve the options. Although the o ...

Can you explain the purpose of the "letter:" included in the code and how it is utilized?

g: function testFunction() { return true; } h: function anotherTestFunction() { } i: console.log('test') I'm intrigued by the mystery of this code snippet. As is written, I am executing it in NodeJS version 16 or higher and trying to un ...

What is the best way to outline the specifications for a component?

I am currently working on a TypeScript component. component @customElement("my-component") export class MyComponent extends LitElement { @property({type: String}) myProperty = "" render() { return html`<p>my-component& ...

The 'isLoading' property is not found in the type 'UseMutationResult<AxiosResponse<any, any>, Error, void, unknown>'.ts(2339)

I'm currently working on implementing a delete functionality that displays a loading state using the useMutate function from tanstackquery. However, I encountered an issue where the loading state is not shown when I click the delete button, even after ...

Having difficulties incorporating a separate library into an Angular project

My typescript library contains the following code, inspired by this singleton example code export class CodeLib { private static _instance: CodeLib; constructor() { } static get instance(): CodeLib { if(!this._instance){ ...

Uncovering TypeScript's Type Inference Power Through the keyof Keyword

Recently, I encountered a situation where I needed to utilize an abstract class. export abstract class ABaseModel { public static isKeyOf<T>(propName: (keyof T)): string { return propName; } } Following that, I also created another class wh ...

Module 'serviceAccountKey.json' could not be located

I'm encountering an issue while trying to incorporate Firebase Functions into my project. The problem lies in importing the service account key from my project. Here is a snippet of my code: import * as admin from 'firebase-admin'; var ser ...

Tips for using the arrow keys to navigate the cursor/caret within an input field

I am trying to create a function that allows the cursor/caret to move inside an input field character by character using the arrow keys (ArrowLeft, ArrowRight) on a keydown event. Current Approach: const handleKeyDown = (e: KeyboardEvent<HTMLInputEle ...

A guide on how to initiate a click event in Angular 5 using JQuery

I am trying to trigger a click event for each element based on its id, but it doesn't seem to be working. Below is the code I am using: ngOnInit() { this.getProductsLists(); } getProductsLists() { this.supplierService.getProductLists() .sub ...

Inferring object types through direct values

This code example has a lot of detail: interface Coordinate { latitude: 40.7128; longitude: -74.0060; } const location: Coordinate = { latitude: 40.7128, longitude: -74.0060, }; // The inferred type would have been // { x: number; y: number; } I ...

The attribute 'subtle' is not found within the definition of 'webcrypto' type

Currently, I am working with Node v17.4 and I am looking to utilize the webcrypto API. Referencing this specific example, I am attempting to include subtle in my project, but TypeScript is throwing an error: Property 'subtle' does not exist on ...

Unable to link to 'amount' because it is not a recognized attribute of 'ng-wrapper'

I recently made some changes to my code and now I'm encountering the error message "Can't bind to 'count' since it isn't a known property of 'ng-container'" Instead of having both the notification component and notificat ...

The Angular application is not functioning properly after running npm start, even though all the necessary packages have

Encountering a perplexing issue with my Angular application. After checking out the code on my new machine, I attempted to run my existing Angular 12 project. However, despite the application running properly in the command prompt, it is not functioning as ...

What are some examples of utilizing paths within the tsconfig.json file?

Exploring the concept of path-mapping within the tsconfig.json file led me to the idea of utilizing it to streamline cumbersome path references: The project layout is unconventional due to its placement in a mono-repository that houses various projects an ...

Divide a given number of elements within an array of arrays

Presented below is an array: [ { "id": "34285952", "labs": [ { "id": "13399-17", "location": "Gambia", "edge": ["5062-4058-8562-294 ...

Combining Multiple TypeScript Declaration Files into an NPM Package for Seamless Importing with index.d.ts

I have a unique package structure that includes: myPackage/ |- types/ | |- type1.d.ts | |- type2.d.ts |- src/ | |- someUtilities.ts |- index.ts |- package.json |- tsconfig.json In my package, the index.ts file is handling imports and exports for all th ...