How do I set class properties in TypeScript using an array of values for initialization?

My constructor has the following structure:

constructor(values: Object = {}) {
        //Constructor initialization
        Object.assign(this, values);
    } 

However, it currently requires named initialization like this :

new Inventory({ Name: "Test", Quantity: 1, Price: 100 })

I am wondering if it can be done directly from an array in this format:

new Inventory(["Test", 1, 100])

Answer №1

Give this a shot

let [Item, Amount, Cost] = ["Example", 1, 50];
createStock({Item, Amount, Cost});

Answer №2

If you want to update the constructor, you can try the following code:

constructor(name: string, quantity: number, price: number) {
    //Initializing the constructor
    Object.assign(this, { Name: name, Quantity: quantity, Price: price });
} 

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

Utilizing the Solana Wallet Key for ArweaveJS Transaction Signing

Is there a method to import a Solana wallet keypair into the JWKInterface according to the node_modules/arweave/node/lib/wallet.d.ts, and then generate an Arweave transaction using await arweave.createTransaction({ data }, jwk);? Metaplex utilizes an API ...

Determining the data type of an object key in Typescript

Is there a way to limit the indexed access type to only return the type of the key specified? interface User { id: string, name: string, age: number, token: string | null, } interface Updates<Schema> { set: Partial<Record< ...

When using Typescript, you may encounter the error message "Declaration file for module 'xmlhttprequest' not found."

When trying to use the following code on Node: import { XMLHttpRequest } from 'xmlhttprequest'; I encountered the following error while compiling with tsc: index.ts|4 col 32 error| 7016[QF available]: Could not find a declaration file for mo ...

typescript max recursion depth restricted to 9 levels

After countless attempts, I finally managed to create a generic type that provides me with all possible combinations of JSON key lists and values. Additionally, I have developed a method to limit the recursion within this type. type EditAction<T,P exten ...

Creating a Typescript union array that utilizes a string enum for defining key names

Can we shorten this statement using string enum to restrict keys: Array<{ [enum.example1]: Example } | { [enum.example2]: Example } | ...> // or equivalent ({ [enum.example1]: Example } | { [enum.example2]: Example } | ...)[]; We can make it more c ...

Exploring through objects extensively and expanding all their values within Angular

I am in need of searching for a specific value within an object graph. Once this value is found, I want to set the 'expanded' property to true on that particular object, as well as on all containing objects up the object graph. For example, give ...

Testing the functionality of functions through unit testing with method decorators using mocha and sinon

I have a class method that looks like this: export class MyClass { @myDecorator() public async createItem(itemId: string, itemOptions: ItemOption[]): Promise<boolean> { // ... // return await create I ...

What is the best way to apply a class to the 'td' element for two specific columns?

I have a rendered row from a database echo "<table border='1' cellpadding='10'>"; echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th></th> <th></th> ...

Set the style of the mat-select element

I'm having an issue with my select option in Angular Material. The options look fine, but when I select one, the strong tag disappears. Can anyone help me style only that part? Thank you in advance. <mat-select formControlName="projectId" ...

How to set up npm to utilize the maven directory format and deploy war files

Embarking on my very first pure front-end project, I decided to deploy it using Java/Maven. To begin, I set up a standard WAR project: │ package.json │ pom.xml │ tsconfig.json │ typings.json │ │ ├───src │ └───main ...

Unable to upload file in angular2 due to empty Body (FormData)

Attempting to upload a photo with Angular2 to my REST Service (Loopback). The Loopback service has been successfully tested using Postman and is able to accept files with the x-www-form-urlencoded header. Below is a simplified version of the service metho ...

Having difficulty transmitting data through SocketIO in NodeJS

My current project involves sending streams of data through SocketIO sockets. I'm working on a Node TS application that will handle large files, so the standard Buffer object won't cut it. Here's the code I have so far: Client Side socket. ...

Exploring the intricacies of pattern matching with JavaScript visualization

I am currently working on improving my pattern matching function by creating a visualizer for it. To achieve this, I need to slow down the execution of each comparison. My approach involves declaring the i and j variables outside of the function so that I ...

Tips for integrating Typescript into a pre-existing Vue 3 project

The contents of my package.json file are as follows: { "name": "view", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve" ...

Is there a way to modify the antd TimePicker to display hours from 00 to 99 instead of the usual 00 to 23 range?

import React, { useState } from "react"; import "./index.css"; import { TimePicker } from "antd"; import type { Dayjs } from "dayjs"; const format = "HH:mm"; const Clock: React.FC = () =& ...

Error in Angular 8: The type of '[object Object]' is an object, whereas NgFor only supports binding to Iterables such as Arrays

I recently started using Angular 8 and I'm dealing with an issue while trying to fetch data from an http get request. I am attempting to iterate through the data using *ngFor but unfortunately encountering this error. Any suggestions on how to resolv ...

Formatting Strings in JavaScript when saving as a .txt file with proper indentation

Utilizing Angular and TypeScript/JavaScript for testing purposes. Each row has been formatted with a newline at the end of the code. formattedStr += car.Name + ' | ' + car.Color + ' | ' + car.Brand + '\r\n' The da ...

How can one determine the data type by analyzing the key value?

I'm attempting to determine the return type of getAllRaces() as () => Race[]. Here is what I have tried so far: type CollectionMap = { races: Race[] horses: Horse[] } type Race = { date: Date } type Horse = { name: string } typ ...

Key Assignment in Vue FireStore - Potential Undefined Object Situation

My goal is to assign Firestore data, passed through props, to a reactive proxy object in Vue. However, I am encountering an error that says: Object is possibly 'undefined'. (property) fireStoreData: Record<string, any> | undefined To strea ...

TypeScript and Next.js failing to properly verify function parameters/arguments

I'm currently tackling a project involving typescript & next.js, and I've run into an issue where function argument types aren't being checked as expected. Below is a snippet of code that illustrates the problem. Despite my expectation ...