Using TypeScript to Initialize Arrays with Objects

Why is it that in TypeScript 1.8, the following code blocks with initializers are considered legal syntax:

class A
{
    public textField: string;
}

var instanceOfClass = new A
{
    textField = "HELLO WORLD"
};

var arrayCollection = new A[]
{
    new A(), new A()
};

...but the following code block is not?

var arrayCollection = new A[]
{
    new A
    {
        textField = "HELLO"
    },
    new A
    {
        textField = "WORLD"
    }
};

It's interesting that TypeScript allows you to initialize arrays and objects, but does not support nesting object initializers within an array initializer.

Answer №1

This code snippet contains an error in typescript syntax:

class A {
    public textField: string;
}

var instanceOfClass = new A {
    textField = "HELLO WORLD"
};

The compiler returns an error message:

Cannot find name 'textField'

To fix this issue, you can set the member value during instantiation by passing it as a constructor parameter:

class A {
    public textField: string;

    constructor(textField: string) {
        this.textField = textField;
    }
}

var instanceOfClass = new A("HELLO WORLD");

Alternatively, you can use the shorter version:

class A {
    constructor(public textField: string) {
        this.textField = textField;
    }
}

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

Challenges in designing components in Angular 2.0 and beyond

Issue at hand - There are two input controls on the same page, each belonging to separate components. When a value is entered into the first input box, it calculates the square value and updates the second input control accordingly. Conversely, if the v ...

Leveraging CSS attribute selectors within JSX using TypeScript

With pure HTML/CSS, I can achieve the following: <div color="red"> red </div> <div color="yellow"> yellow </div> div[color="red"] { color: red; } div[color="yellow"] { color: yellow; ...

Finding the Biggest Number in an Array

I've come up with a solution using Math.max(), but I'm curious why the following approach isn't working. array = [4, 5, 1, 3] for (var i = 0; i < array.length; i++) { var num = 0; if (array[i] > num) { num = array[i]; } } ...

Export a NumPy array to a comma-separated values file

What is the best way to save a 2D NumPy array as a csv file in a readable format? ...

Navigating arrays and managing null values through loops

My array, named myArray, contains various data elements: Array ([0] =>( Number => 02348 Food => Array ( [0] => orange [1] => apple [2] => plum ) State => Array ( ...

Exploring the filter method in arrays to selectively print specific values of an object

const array = [ { value: "Value one", label: "Value at one" }, { value: "Value 2", label: "Value at 2" }, { value: "" , label: "Value at 3" } ...

Error: Unable to access 'nativeElement' property from undefined object when trying to read HTML element in Angular with Jasmine testing

There is a failure in the below case, while the same scenario passes in another location. it('login labels', () => { const terms = fixture.nativeElement as HTMLElement; expect(terms.querySelector('#LoginUsernameLabel')?.tex ...

Error: Issue determining the type of variable. Unable to eliminate type 'any'

I am trying to load some widgets from a template object (possibly JSON in the future). Here's an example: type RectangleTemplate = { name: 'Rectangle'; props: { width: number; height: number; } }; type ButtonTemplate = { nam ...

Here is a guide on showcasing information obtained from ASP.NET API in Angular version 13

My goal is to fetch motorcycle data from a web API and showcase it in my Angular project. ASP.NET Framework Web API 4.7 Angular CLI: 13.3.7 Angular: 13.3.11 On the Web API end: Controller: [EnableCors(origins: "*", headers: "*", ...

How to extract a specific field from an object in an array using MongoDB's $first operator, excluding the use of $getField

I am currently working with mongo version 4.4 and I need to achieve a specific result in my projection: { districtId: 'xkj1', firstCollegeId: '123' } My goal is to only retrieve the FIRST element that is classified as type: ' ...

The type 'myInterface' cannot be assigned to the type 'NgIterable<any> | null | undefined' in Angular

I am facing an issue that is causing confusion for me. I have a JSON data and I created an interface for it, but when I try to iterate through it, I encounter an error in my HTML. The structure of the JSON file seems quite complex to me. Thank you for yo ...

Angular 6's subscribe method is causing the UI to not update

I'm currently facing an issue where my component does not refresh the UI after I input data. I always have to manually refresh the page to see the changes. I suspect there might be a problem with the .subscribe method in Angular 6. Previously, when I ...

The array_search function is not functioning as anticipated when used with a multi-dimensional array

Looking for the key of a value in a multidimensional array? Check out the example below: $array = array( 'USD' => array ( 0 => 1.79, 1 => 3.58, 2 => 5.37, 3 => 7.16, 4 => 8.95, ), 'CAD ...

A more efficient approach to specifying types for the 'navigation' object in React Native's Stack Navigator

Struggling with modularizing prop types in React Navigation, particularly when using TypeScript. The Typescript section of the React Navigation documentation suggests defining types for each screen props in this manner: //types.ts export type RootStackPara ...

Tips for effectively parsing a sizable JSON document (40mb) using SWIFT

I have encountered a challenge while attempting to parse a large JSON file that exceeds the size of 40mb. Upon loading this JSON data in viewdidload(), it results in a significant memory spike up to 300mb. Are there any recommended libraries or efficient t ...

Encountered an issue: The type 'Usersinterface' is not meeting the document constraints

Below is a screenshot displaying an error: https://i.stack.imgur.com/VYzT1.png The code for the usersinterface is as follows: export class Usersinterface { readonly username: string; readonly password: string; } Next, here is the code for users ...

Arrangements of inputs in HTML

<input name="foo[]" ... > While I have utilized these in the past, I am curious about its official name and whether there is a specific specification for it. Despite my search efforts within the HTML 4.01 Spec, the term "array" seems to be most com ...

Validation error from Express-validator may result in TypeScript error: the request.query object could potentially be undefined

Recently, as I was developing a Node.js app using express, I decided to enhance it with express-validator. Despite being new to express-validator, the warnings it generated perplexed me due to its lack of detailed documentation. To illustrate my point, he ...

Does the method in the superclass "not exist" within this type....?

Our TS application utilizes a JavaScript library, for which we crafted a .d.ts file to integrate it with TypeScript. Initially, the file resided in a "typings" directory within the project and everything operated smoothly. Subsequently, we opted to relocat ...

Leveraging the power of both TypeScript 2.3 and 2.4 concurrently within Visual Studio 2015.3 on a single machine

Can TS 2.3 and TS 2.4 be used on the same machine simultaneously? For example, I have one project in VS 2015.3 compiling with TS 2.3 and another project compiling with the latest TypeScript version (TS 2.4). I recently installed TypeScript 2.4, which aut ...