Instantiate a fresh object using the new keyword followed by the Class constructor, and if desired,

I'm looking for a class that I can easily create new instances from and optionally assign properties using the constructor.

For instance:

class Person {
  name: string;
  age: number;
  constructor(props: {name?: string, age?: number}) {
    this.name = props?.name?? "";
    this.age = props?.age?? 0;
  }
}

const person1 = new Person({name:"Pete"})

Is there a more streamlined approach to achieve this?

Answer №1

If we define "elegant" as having a DRY syntax, then there is little room for improvement. The example below demonstrates how you can streamline the constructor body implementation by utilizing default parameters and a self-referential type modified by the Partial utility:

TS Playground

class Person {
  age: number;
  name: string;

  constructor({ age = 0, name = "" }: Partial<Person> = {}) {
    this.age = age;
    this.name = name;
  }
}

console.log(new Person({ name: "Pete" })); // { age: 0, name: "Pete" }
console.log(new Person({ age: 155 })); // { age: 155, name: "" }
console.log(new Person({ age: 155, name: "Pete" })); // { age: 155, name: "Pete" }
console.log(new Person({})); // { age: 0, name: "" }
console.log(new Person()); // { age: 0, name: "" }


TypeScript also offers parameter properties. However, this concept does not apply to the given example because the single constructor parameter is an object type, which cannot be assigned to any members of the class itself. By restructuring the class constructor to use ordered parameters for each field (instead of an object parameter), you could make use of this syntax pattern.

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

Navbar Growth Effect

I'm attempting to create an expanding effect in my navbar using Angular. When I click on "show information," the content should slide up. The issue is that the top part of my footer does not follow the effect. I have tried something like: <foot ...

Error message shows explicit Typescript type instead of using generic type name

I am looking to use a more explicit name such as userId instead of the type number in my error message for error types. export const primaryKey: PrimaryKey = `CONSUMPTION#123a4`; // The error 'Type ""CONSUMPTION#123a4"" is not assignable to ...

Switching the Checkbox Data Binding Feature in Angular

I am looking to send a value based on a toggle switch checkbox selection between Hourly or Salary. How can I incorporate this into the form below? html <div class="row"> <div class="col-sm-6"> <div cl ...

How can I move the cursor to the beginning of a long string in Mat-autocomplete when it appears at the end?

I'm struggling to figure out how to execute a code snippet for my Angular app on Stack Overflow. Specifically, I am using mat-autocomplete. When I select a name that is 128 characters long, the cursor appears at the end of the selected string instead ...

Difficulty Determining Literal Types that Expand a Union of Basic Data Types

Below are the components and function I am working with: interface ILabel<T> { readonly label: string; readonly key: T } interface IProps<T> { readonly labels: Array<ILabel<T>>; readonly defaultValue: T; readonly onChange ...

The Angular 6 View does not reflect changes made to a variable inside a subscribe block

Why isn't the view reflecting changes when a variable is updated within a subscribe function? Here's my code snippet: example.component.ts testVariable: string; ngOnInit() { this.testVariable = 'foo'; this.someService.someO ...

The scale line on the OpenLayers map displays the same metrics twice, even when the zoom level is different

When using the Openlayers Map scale line in Metric units, a specific zoom rate may be repeated twice during the zoom event, even though the actual zoom-in resolution varies on the map. In the provided link, you can observe that the zoom rates of 5km and ...

Sending the HTML input value to a Knockout view

Can someone assist me with a dilemma I'm facing? Within CRM on Demand, I have a view that needs to extract values from CRM input fields to conduct a search against CRM via web service. If duplicate records are found, the view should display them. Be ...

When validating storage content, session value appears as null

I have been working on developing an Ionic app that requires creating a session for user login. The goal is to store the user's name upon logging in, so it can be checked later if the user is still logged in. I have created a model class and a user cl ...

Why isn't my Promise fulfilling its purpose?

Having trouble with promises, I believe I grasp the concept but it's not functioning as expected in my project. Here is a snippet of my code : (I am working with TypeScript using Angular 2 and Ionic 2) ngOnInit() { Promise.resolve(this.loadStatut ...

Transferring information via Segments in Ionic 3

I'm facing a challenge where I need to transfer a single ion-card from the "drafts" segment to the "sent" segment by simply clicking a button. However, I am unsure of how to achieve this task seamlessly. Check out this image for reference. ...

What causes an ObjectUnsubscribedError to be triggered when removing and then re-adding a child component in Angular?

Within a parent component, there is a list: items: SomeType; The values of this list are obtained from a service: this.someService.items$.subscribe(items => { this.items = items; }); At some point, the list is updated with new criteria: this.some ...

Is it possible for me to make the default export anonymous?

Why bother naming the export if you already have a file with the default export name? This seems redundant and goes against the DRY principle. While there is a rule that discourages anonymous default exports, how can we enforce an error when someone does ...

Guide on changing the color of the selected item in mat-nav-list within angular 6

Recently diving into Angular 6 and facing an issue with my mat-toolbar integrated with mat-sidenav. Everything seems to be functioning fine, but I'm looking to customize the color for the active item in the side nav menu. Currently, all items have a ...

What's causing Angular to not display my CSS properly?

I am encountering an issue with the angular2-seed application. It seems unable to render my css when I place it in the index.html. index.html <!DOCTYPE html> <html lang="en"> <head> <base href="<%= APP_BASE %>"> < ...

Tips for determining if a key is present in local storage:

I need to set a key value, but only if it doesn't already exist. In my component1.ts file, I am assigning the key and value in the constructor. However, I want to include a condition that this action should only be taken if the key is not already pre ...

The type definition file for 'jest' cannot be located, despite the fact that jest has been successfully installed

SOLUTION STRATEGY: If you encounter a similar issue and are looking for a more comprehensive solution rather than quick fixes, consider recreating the repository. While it involves more effort initially, it can prevent future issues. In my case, the repos ...

Utilize nested object models as parameters in TypeScript requests

Trying to pass request parameters using model structure in typescript. It works fine for non-nested objects, but encountering issues with nested arrays as shown below: export class exampleModel{ products: [ { name: string, ...

Creating a function that is accessible to the entire module

Creating a universal function in a file that is not a module: example.ts: function example() {} You can easily call this function from another file, say test.ts, without needing to import the function from example.ts: test.ts: example(); // calling univ ...

The function nested within a constructor that includes `this.route` is not assigning it as an array

this.routeHandler = function () { let stations = ['KSFM', 'KPWM'] let coordinates = []; let allCoords = []; if (Array.isArray(stations) == true) { for (let i = 0; i < fetchRoute().length; i++) { fo ...