Do you have to use "new MyClass" when initializing an array in Typescript?

In this example, I am creating a class called Person. I have opted to use a class instead of a type alias because the constructor for this class is more complex and contains functions.

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

To initialize an array of instances of this class, I use the following code :

persons: Array<Person> = [
        new Person("Joe",30),
        new Person("Jack",40)
]

I'm curious if there is a way to avoid repeating the new Person multiple times. Any suggestions would be greatly appreciated. Thank you!

Answer №1

In case this is a common scenario, you have the option to develop a helper function that allows you to specify a class and its constructor parameters:

class User {
    username: string;
    id: number;
    constructor(username: string, id: number) {
        this.username = username;
        this.id = id;
    }
}


function createMany<T, P extends any[]>(cls: new (...p: P) => T, ...p: Array<P>): Array<T> {
    return p.map(a => new cls(...a))
}

var users: Array<User> = createMany(User,
    ["Alice", 101],
    ["Bob", 202]
);

Playground Link

If your class mainly consists of data fields, it's advisable to use an interface as per TypeScript conventions:


interface User {
    username: string;
    id: number;
}

var users: Array<User> = [
    { username: "Alice", id: 101 },
    { username: "Bob", id: 202 },
];

Playground Link

Answer №2

Your objective may not be entirely clear, but if you are manually entering the values (such as Joe, Jack, etc), consider storing them in an array and utilizing Array.map() to associate them with instances of Person, like so:

const personList = [
    {name: 'Joe', age: 30},
    {name: 'Jack', age: 40}
]

persons: Array<Person> = personList.map((person) => new Person(person.name, person.age))

I hope this suggestion proves helpful.


To streamline the class definition, you can include access modifiers within the constructor:

class Person {
    constructor(public name: string, public age: number) {}
    //                  ^^^ this.name       ^^^ this.age
}

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

Sign up for the identical Observable within a Child Component in Angular 2 using TypeScript

This question may seem simple, but as a newcomer to Angular 2, I often find myself needing more explanation despite the good examples and tutorials available. Within a component, I have an observable that gets updated periodically. While I've simplif ...

The subsequent menu selection will be based on the chosen menu value

I am attempting to accomplish the following: https://i.sstatic.net/JffUWC02.png Essentially, I need a select options menu with labels where selecting an option will display a corresponding value. These values should then become labels for a second selec ...

What is the best way to retrieve the Base64 string from a FileReader in NextJs using typescript?

My goal is to extract a string from an object I am receiving in the response. const convertFileToBase64 = (file: File): Promise<string> => { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.r ...

Angular Bootstrap causes misalignment of table column headings based on different properties in object

I have an object with two properties: person and vehicle. Both properties consist of arrays of data. I have separate column headings for the person and vehicle properties and display the data in tabular form. However, the column headings for both propertie ...

Display the highlighted text within the input field

Is there a library available that can create an input field with a suggestions dropdown for Male and Female where typing "M" will highlight the letters "ale," allowing for autopopulation when clicked or tabbed? The same functionality should apply for typin ...

What causes an error when the App is enclosed within a Provider component?

What is causing the error when wrapping the App in Provider? Are there any additional changes or additions needed? Error: "could not find react-redux context value; please ensure the component is wrapped in a @Provider@" import React from ' ...

Is there a way for me to determine if there are elements in one object array that exist in another object

Is there a method to check if two object arrays have any common elements, and if so, find the intersecting object? Similar to a Contains function. For instance, in the provided example, ProductId3 in Object Array 1 is also present in Object Array 2. I&apo ...

Tips for adjusting the dimensions of a map within the app.component.html

Within the code snippet below, my aim is to adjust the width and height of the map using the style tag shown here: <style> #map3 .map { width: 100%; height:90px; } </style> Despite trying various values for width an ...

Exploring the relationship between two entities in Angular 7 using Typescript

Creating a Reactive form for user registration in Angular involves setting up the form data object separately from the viewmodel object. https://i.sstatic.net/ERlYa.png export interface RegisterViewModel { UserName: string; Email: string; Password: strin ...

Allow Visual Studio Code to create a constructor for Typescript class

When developing Angular 2 apps in Typescript using Visual Studio Code, one common task is writing constructors with their parameter list. Is there a way to save time and effort on this? It would be really helpful if the IDE could automatically generate th ...

Expo constants failing to load on web due to unresolved manifest object issue

When setting up Firebase Auth in my expo app (using Google Auth), I needed to store my firebase variables in a .env file containing API_KEYS, AuthDomain, and more. To access these environment variables, I utilized expo constants in my firebase.ts file. Ini ...

How can TypeScript be used to access a state object conditionally using an array?

I have an issue with my object that has an extended state object. I created an array of values to check using a for of loop, but I am having trouble making the array value compatible with the state object's key. How can I inform TypeScript that the va ...

Does the Typescript interface align with the specifications of this object?

I'm looking to define a TypeScript Interface for objects similar to these: { "id": 34728, "url": "https://example.com/image.jpg", "commonNames": { "de": ["Apfel", "Kulturapfel"], "en": ["apple"], "th": ["แอปเปิล"] }, ...

Guide on validating multiple preselected checkboxes using Angular 8 reactive forms

I have a problem with validating checkboxes in my Angular application. The checkboxes are generated dynamically from an array using ngFor loop, and I want to make sure that at least one checkbox is selected before the form can be submitted. The validatio ...

Can you explain the use of parentheses in a typescript type when defining a key?

Could someone provide an instance of an object that matches the TypeScript type below? I'm a bit confused because I've only worked with interfaces before and have only seen square brackets. type Hash = { (data: Uint8Array): Uint8Array blockLe ...

VPS mysteriously terminates TypeScript compilation process without any apparent error

I've encountered an issue while trying to compile my TypeScript /src folder into the /dist folder. The process works smoothly on my local machine, but when I clone the repo onto my VPS (Ubuntu Server 22.04), install npm, and run the compile script, it ...

The Vue and Typescript webpage is not appearing in the GAS sidemenu template

I am tasked with developing an application for Google Sides using Vue + Typescript to enhance its functionality with an extra menu feature. You can find a sample without Typescript here. The result is visible in this screenshot: https://gyazo.com/ed417ddd1 ...

Utilizing Angular 11's HostListener to capture click events and retrieve the value of an object

Using the HostListener directive, I am listening for the click event on elements of the DOM. @HostListener('click', ['$event.target']) onClick(e) { console.log("event", e) } Upon clicking a button tag, the "e" object contains the fol ...

Is there a built-in feature in npm or yarn that automatically installs @types when they are present in Typescript projects?

Is there a feature in npm or yarn that automatically installs @types/* for packages without their own types, in Typescript projects? For example: //package.json { // ... "installTypes": true } // installing package yarn add ABC <- will install A ...

Is there a way for me to retrieve the username of an object from a select list?

I am working with a select list that contains names, and I need to extract the name instead of the ID in order to insert it into the database. Below is my TypeScript file: selectUser() { this.UtilisateurService.findAll().then((res) => { let ...