Inquiry regarding Typescript's array of types

While researching how to declare arrays of types online, I came across the following example:

arrayVar: Array<Type>

Seems simple enough, so I attempted to declare my variable like this:

transactions: Transactions = { total : 0, list: Array<Transaction>};

However, this resulted in a syntax error. After some trial and error, I ended up using this instead:

transactions: Transactions = { total : 0, list: Array<Transaction>()};

This solution compiles and functions as expected. Now, my question is: what is the purpose of the parentheses, and why does the declaration not work without them?

Answer №1

When you work with a class called X and invoke X(), you are actually invoking the constructor method of that specific class. To create a new array, you should use Array() but with a specified type indicator within <type>, which then initializes the list element.

If you find the syntax above difficult, an alternative is to use square brackets:

transactions: Transactions = { total : 0, list: Transaction[]};

Furthermore, it appears that your 'transactions' variable is essentially an array. If all you need is the total count, simply determine the number of elements in the array as follows:

transactions: Transaction[];
transactions.push(transA);
transactions.push(transB);
let total = transactions.length();

Answer №2

Take a look at this

export type Transaction={};
export type Transactions={
  total:number;
  list:Transaction[]; //or Array<Transaction>
}

//what was done - and what was correct

let transactions: Transactions = {total:0,list:[]}; //empty array

//attempt that resulted in failure
let badTx: Transactions={total:0,list:Transaction[]}; //type `Transaction[]`

Clearly, the mistake was trying to assign a TYPE of Transaction[] when an array (of such type) was expected. Hence, the error.

The parentheses in the question are just part of constructor invocation and would be equivalent to new Array<Transaction>

Try it out on TS Playground

In short - Array is a type, while Array<x>() represents a newly created instance of Array<x>

Answer №3

Using parentheses in this context indicates a function call, specifically to instantiate a new empty array that aligns with your type definition by having no members.

Consider the following declaration:


transactions: Transactions = { total : 0, list: Array<Transaction>};

In this case, you are actually passing the Array function itself instead of an instance of it. This means that it does not meet the expectation of list being an array instance as per the type definition.

Just so you know, by declaring the assigned object as the Transactions type, list will automatically be understood as an array of Transaction type if it is defined there. Therefore, there is no need to specify the member type when calling Array.


transactions: Transactions = { total : 0, list: Array()};

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

Incorporate Angular frontend into current website or project

I've successfully built a website using bootstrap, but now I'm looking to integrate Angular in order to transform it into a single page application. The goal is that when a user clicks on a link, only the necessary content will be loaded from the ...

Clearing dropdown values when navigating back on a page in Angular 6: A step-by-step guide

Image Within the App Component, I have implemented a dropdown list. When an option is selected from the dropdown, it should navigate to another page using routing. Additionally, upon clicking the back button, it should return the user to the app compone ...

Encountering a 400 bad request error while trying to retrieve an authentication token from an API url in Angular

I encountered a problem in my Angular 6 application where I am receiving an Http 400 Bad Request error when attempting to call the API url for login token. The interesting thing is that the API works perfectly fine when accessed through POSTMAN. However, ...

Shifting focus among an array of standard <input> controls with each keystroke

When working with Angular, I encountered a situation where I have an array of arrays of numbers, as shown below: [ [1,1,1,1], [1,1,1,1] ] In my HTML file, I am using ngFor to generate input controls like this: <table> <tbody> ...

Tips for choosing a subset of objects within a larger array of objects and generating a new array from them?

I am working with an array of 3586 objects, each containing various products. How can I create and store a new array that only includes the products from a specific index? console.log listarPorReferencia() { this.linxService.listarPorReferencia().subs ...

Angular2 with Webpack causes duplication of styles in the header

I'm currently working on integrating Angular2 with universal + webpack, but I have encountered an issue where styles are being loaded twice in the head element. I haven't made any changes to the git repo that I forked from. You can find it here: ...

I am looking to personalize a Material UI button within a class component using TypeScript in Material UI v4. Can you provide guidance on how to achieve this customization?

const styling = { base: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, ...

How can I simulate or manipulate the element's scrollHeight and clientHeight in testing scenarios?

In my JavaScript code, I have a function that checks if an HTML paragraph element, 'el', is a certain size by comparing its scrollHeight and clientHeight properties: function isOverflow(element: string): boolean { const el = document.getEleme ...

Sorting character values in TypeScript using ascending and descending order in a JSON array

In my dataset of homes, I have the following information: var homes = [ { "h_id": "3","city": "Dallas","state": "YYYY","zip": "75201","price": "162500" }, { "h_id": "4","city": "CA","state": "ZZZZ","zip": "90210","price": "319250" }, { "h ...

Updating a specific field in a Firestore document: A step-by-step guide

Is there a way to retrieve and edit a particular field in Angular Firestore? https://i.sstatic.net/fiElK.png ...

Generating a compressed tar.gz file with a version-specific name using Angular CLI post-build

Here's what I'm trying to do: I want to generate a .tar.gz file once my project is built, and I need the name of the file to be based on the version of the project. I attempted using npm pack, but it only takes the name of the dist folder and cr ...

Retrieve data using Angular FileReader's onloadend method and return the result

When working with audio recording in Angular, I encountered a challenge with my code. The goal was to record audio, obtain the blob, and convert it to base64 using FileReader. However, I struggled with returning this base64 data from the onloadend method o ...

Angular Universal (SSR) 'Selectors were not applied as rules were not followed'

Steps to Reproduce: ng new testproject --style scss cd testproject ng add @ng-bootstrap/ng-bootstrap npm run build This issue is not limited to ng-bootstrap, it can occur with other frameworks like bootstrap or tailwind that use SCSS. Error Description: ...

Creating a regular expression for validating phone numbers with a designated country code

Trying to create a regular expression for a specific country code and phone number format. const regexCountryCode = new RegExp('^\\+(48)[0-9]{9}$'); console.log( regexCountryCode.test(String(+48124223232)) ); My goal is to va ...

Instead of relying on the valueChanges method, consider using setValue or patchValue in Angular 4 to monitor

I've implemented a floating point directive on fields in a reactive form to enhance readability by adding commas every 1000 and appending .00 to field values. This formatting works well, with onBlur triggering the formatting and onFocus removing it. ...

The data type 'string' cannot be assigned to the data type 'undefined'

These are the different types available: export type ButtonProperties = { style?: 'normal' | 'flat' | 'primary'; negative?: boolean; size?: 'small' | 'big'; spinner?: boolean; } export type ...

Combining pixijs with TypeScript in Ionic 2 using npm

To begin, I ran the command npm install -g ionic Followed by ionic start pixiApp blank --v2 Navigated to the pixiApp directory with cd pixiApp Installed necessary dependencies using npm install Added a specific version of pixi.js (4.1.0) with npm install p ...

Retrieve data from a table within an Angular component

Struggling with the ng2-smart-table library, I am facing challenges in passing values entered in the edit line to a custom component: Refer to the code snippet below for passing Maximum and Minimum Temperature values to the SmartTableEditorFunctionsCompon ...

How to Use an Object Created from a Different Class in TypeScript

Scenario In the development process, I am using an auth.service.ts. This service is responsible for fetching user information from the database upon login. The retrieved data is then used to create a new user object. Here is a snippet of the code: user: ...

Angular 2 Date Input failing to bind to date input value

Having an issue with setting up a form as the Date input in my HTML is not binding to the object's date value, even though I am using [(ngModel)] Here is the HTML code snippet: <input type='date' #myDate [(ngModel)]='demoUser.date& ...