Most effective method for initiating model class attributes

Is there a more efficient way to initialize model classes without explicitly defining each member as undefined?

The original concept was to be able to simply use super(data); in extended classes.

class Model {
    construct(data: any) {
        Object.keys(this).forEach(key => {
            this[key] = data[key];
        });
    }
}

class User extends Model {

    id: number = undefined;
    name: string = undefined;

    constructor(data: any) {
        super();
        this.construct(data);
    } 
}

Answer №1

I always opt for using interfaces. Check out this typescript playground for a demonstration.

interface Thing {
    numberProp: number;
    stringProp: string;
    notRequiredStringProp?: string;
    anotherNotRequiredStringProp?: string;
}

let myThing: Thing = {
    numberProp: 31232,
    stringProp: 'Hello'
};

alert(myThing.numberProp);
alert(myThing.stringProp);
alert(myThing.notRequiredStringProp);
alert(myThing.anotherNotRequiredStringProp);

UPDATE

Here's how you can retrieve the data through a web service without needing to invoke a constructor.

export class ThingService {
   constructor(private httpClient: HttpClient){}

   // Retrieves a collection of "Thing"
   getThings(): Observable<Thing[]>{
      return this.httpClient.get('api/things')
   }

   // Retrieves a single "Thing" based on its unique identifier
   getThingById(id: number): Observable<Thing>{
      return this.httpClient.get('api/things/' + id)
   }
}

Then in a component, usage could be:

ngOnInit(){
  this.thingService.getThings().subscribe((things: Thing[]) => {
      //do something with things
  });
} 

Answer №2

If you're looking to create a constructor with optional parameters and public/private modifiers, you can do so to have a robust model even when calling the constructor without parameters.

class User {    
    constructor(public id?: any, public name? : any) {} 
}

This can be achieved more concisely as:

class User {
    constructor(id, name) {
        this.id = id;
        this.name = name;
    }
}

To convert an object into a User instance, you can implement a bind method using Object.assign:

class User {    
    constructor(public id?: any, public name? : any) {} 

    bind(object: any): Equipe {
        return Object.assign(this, object);
    }  

}

For a truly solid model, consider using Object.seal within the bind method to prevent dynamic property additions:

class User {    
    constructor(public id?: any, public name? : any) {} 

    bind(object: any): Equipe {
        return Object.assign(Object.seal(this), object);
    }  
} 

You can now instantiate a User object like this:

let user = new User(); // user = {id: undefined, name: undefined}

and bind it to another object:

let user = new User().bind({id: 1, name: 'bob'})

Answer №3

In case there is a lack of logic, one can easily implement the following in the constructor:

constructor( info: any){
     Object.assign(this, info);
}

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

Having trouble sending the request body via next-http-proxy-middleware

Recently, I've been attempting to develop a frontend using nextjs that communicates with a Java backend. To achieve this, I'm utilizing the npm package next-http-proxy-middleware. However, it seems like either my request body is getting lost in t ...

Altering the dimensions of radio buttons

I am a newcomer to using material-ui. I am currently working on incorporating radio buttons in a component and would like to reduce its size. While inspecting it in Chrome, I was able to adjust the width of the svg icon (1em). However, I am unsure how to a ...

TS1261: The file name 'xxx' that is already included is different from the file name 'xxx' only in terms of casing

In my project, there is a file located at /app/client/modules/activity/pages/New/hooks.ts. The folder name is New, with the first letter capitalized. During the webpack build process, I encountered the following error: ERROR in /root/app/client/modules/ac ...

defining initial state values for a React class component using TypeScript

Here is the current state of the component: class Feed extends Component<FeedProps, FeedState> { constructor(props) { super(props); this.state = { isEditing: false, posts: [], totalPosts: 0, editPost: null, sta ...

What is the solution for the warning "Solid's reactivity is broken when destructuring component props"?

Just starting out with SolidJS and encountering an issue with my UI setup import { render } from "solid-js/web"; import { createSignal, Show } from "solid-js"; import { createStore } from 'solid-js/store'; function Form() { ...

Angular always ensures that the Ionic4 type homepage is consistently loaded

My Ionic4 App seems to consistently load the homepage despite my efforts to set different initializations such as loadChildren, component, and redirectTo. The issue persists with always loading the homepage. .app-routing.module.ts const routes: Routes = ...

Sequelize v5 & Typescript Model Loader

Having previous experience with Sequelize for projects (v4), I am now venturing into starting a new project using Sequelize v5 & Typescript. I have been following Sequelize's documentation on how to define Models at: https://sequelize.org/master/ ...

Angular drag and drop functionality combined with interactive buttons for list management

Looking to create an Angular component for re-sorting objects by dragging from one list to another? I also need this component to include buttons for additional functionality. I've explored the various drag and drop components available on the Angula ...

What are the drawbacks of starting with Angular CLI?

Contemplating whether to incorporate Angular CLI into my upcoming project has been on my mind. My main motivation for considering it is to bypass the complexities of setting up a new project and instead focus on mastering the new version of Angular while c ...

Decorators in Angular 9 do not have the capability to support function expressions

Currently, I am working with Angular 9 and facing an issue while generating dynamic routes values during runtime. I have implemented a ComplexUrlRouter to achieve this functionality and integrated it into my Route configuration. However, I encountered the ...

How Vue3 enables components to share props

Having recently made the switch from Vue2 to Vue3, I find myself a bit perplexed about the best approach for sharing props among multiple components. My goal is to create input components that can share common props such as "type", "name", and so on. Previ ...

Attempting to create a TypeScript + React component that can accept multiple types of props, but running into the issue where only the common prop is accessible

I am looking to create a component named Foo that can accept two different sets of props: Foo({a: 'a'}) Foo({a: 'a', b: 'b', c:'c'}) The prop {a: 'a'} is mandatory. These scenarios should be considered i ...

Develop a fresh category inspired by the properties of objects

Let's tackle the challenge of constructing a new type in Typescript based on an descriptive object named schema, which contains all the requirements expressed within it. Here is my proposed solution: type ConfigParameter<IdType, ValueType> = Re ...

Issue: FlashMessagesService not provided - NullInjectorError

Utilizing Angular 2 flash messages to showcase a message when the user clicks on the logout button has been quite the challenge. Despite adding a provider in navbar.component.ts and conducting various experiments, I still encounter the same error. Outline ...

Could this be a problem within my recursive function?

Struggling to iterate through a stack of HTML Elements, I attempted to write a recursive function with no success. In the code snippet below, I'm facing challenges in returning a value from an if statement and ultimately from the function itself. Wh ...

The real-time updates on an Angular 2 website can be seen across multiple devices simultaneously

Just getting started with Angular 2 and ran into an interesting issue. When setting up my website, NPM defaults the server to http://localhost:3000. To test the site on another computer, I tried accessing it using my IP address http://10.x.x.x:3000 and eve ...

Error encountered within eot file using file-loader and webpack

I am facing an issue while trying to integrate React Rainbow Components with Next.js (TypeScript). I encountered a problem with importing fonts, which led me to use webpack along with the url-loader. However, despite my efforts, I keep encountering the er ...

What causes the Angular child component (navbar) to no longer refresh the view after a route change?

Hello everyone, I'm excited to ask my first question here. Currently, I am working on developing a social network using the MEAN stack and socket.io. One of the challenges I am facing is displaying the number of unread notifications and messages next ...

Implementing TypeScript in an Asp.net Core ReactJS application`s configuration

After using Visual Studio 2022 to create an asp.net core Reactjs project, I discovered that everything was written in javascript instead of typescript. Is there a way to switch this project over to typescript? ...

There was an error while compiling the Angular application using ng serve and ng build. The error occurred in the module build and seemed to be related to the Sass loader. The specific issue was an expected "}" that was

After experimenting with various nodejs versions and npm using nvm, attempting to downgrade/upgrade ng core and ng cli, trying to install sass-node and removing sass (and vice versa), I have exhausted all options. Despite searching through numerous Stack ...