Set the array as the object attribute

Transitioning my app from AngularJs to Angular 4 has been quite a challenge.

I've noticed that the type of statements I frequently used in my code are now failing in Angular 4 (TypeScript):

Update: The following lines were previously used in AngularJS

var dorm = {};
dorm.DormitoryAddresses = [];

When attempting this in my Angular4 component class:

this.dorm = {};
this.dorm.DormitoryAddresses = [];

An error is thrown: Property DormitoryAddresses does not exist :(

Answer №1

When working with Typescript, the type of a variable can be determined through assignment inference.

If you want to step outside of the type system altogether (although not recommended), you can use the keyword "any":

let lodging: any = {};
lodging.LodgingAddresses = [];

Alternatively, you can explicitly specify the type of the variable:

let lodging: { LodgingAddresses?: any[] } = {}; // using "any," but a more specific type can be used
lodging.LodgingAddresses = [];

You can also utilize a named interface:

interface Lodging { LodgingAddresses?: any[] } // again, using "any" for demonstration purposes
let lodging: Lodging = {}; 
lodging.LodgingAddresses = [];

If possible, initializing the variable all at once will allow Typescript to infer the correct type:

let lodging = { LodgingAddresses: [] }

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

Adding a new property to the Express request object type: what you need to know

Recently, I developed a custom middleware that executes specific logic tasks. It operates by transforming the keys to values and vice versa within the req.body. Both the keys and values are strings, with built-in validation measures in place for safety. T ...

Creating a generic component map resolver for flexible applications

Currently, I am engaged in a project where the backend allows for the modeling of dynamic content that is later displayed as Components on the frontend. Everything seems to be functioning well, except when dealing with models where the dynamic content con ...

Tips for ensuring confidential communication between clients and servers

My project utilizes AngularJS on the client-side and Express JS on the server-side for data communication using the http post method. Currently, when a http request is sent, the server responds with JSON data that gets displayed in the client browser. I wa ...

Tips for incorporating buttons into columns on ng2-table within Angular 2

I am in need of a table with an edit button in every column using ng2. However, I have encountered an issue placing the buttons at the end of each column. Here is my HTML code: <ng-table [config]="config.sorting" (tableChanged)="onChangeTable(co ...

Error encountered while upgrading to Angular 5: splitHash issue

Currently in the process of transitioning from Angular 4.x to 5.x, I have encountered the following error: main.81bcdf404dc22078865d.bundle.js:1 Uncaught TypeError: i.splitHash is not a function at Object.t.parseUrl (main.81bcdf404dc22078865d.bundle.js:1) ...

Launching the VS Code debugger feels like inviting my web app to a party

Recently, I've noticed an issue while debugging my vs code. It appears that the debugger hosts my app without me even running npm start. This behavior allows me to access my app in Chrome without initiating npm start. Normally, my app runs on port 300 ...

What is causing the element to disappear in this basic Angular Material Sidenav component when using css border-radius? Check out the demo to see the issue in action

I have a question regarding the Angular Material Sidenav component. I noticed that in the code below, when I increase the border-radius property to a certain value, the element seems to disappear. <mat-drawer-container class="example-container" ...

Possibility for Automatic Type Inference in Generics

Is there a way to have a method infer the type of function parameter without specifying its generic? Currently it is 'GET' | 'POST', but I only need the literal 'GET' const func = <Params, Method extends "GET" | & ...

Having trouble getting undefined values for keys while attempting to retrieve all the data from Firebase DB with Angular

Currently, I have code that is fetching records from the Firebase database using both Angular and Ionic. The code functions properly, but it does not provide me with the keys for each record. Instead, it returns 'undefined'. I have researched s ...

Using a dictionary of class types as input and returning a dictionary of their corresponding instances

Is there a way to create a function that takes a dictionary with class values as an argument and returns a dictionary of their instances? For example: classes C1, C2 function f: ({ name1: C1, name2: C2 }): ({ name1: new C1() name2: new C2 ...

Error message: Unable to access property 'post' from undefined - Angular 2

Here is the snippet of code in my component file: import { Component, Injectable, Inject, OnInit, OnDestroy, EventEmitter, Output } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import & ...

When using `JSON.stringify`, the resulting data may vary from the original object

Here is the code snippet in question: console.log("444444: ", profile, JSON.stringify(profile)) Upon checking the log output: https://i.stack.imgur.com/LzalV.png I am trying to understand why I cannot see the value: [0] present Additionally, ...

Invoke the function when the user inputs text into the textbox

<textarea name="" id="" #text cols="30" (keydown)="WordCounter()" (change)="WordCounter()" rows="8" [(ngModel)]="user_text" placeholder="Type something here"></textare ...

Incorporate a module that was developed locally into your project

Attempting to incorporate a locally developed Angular project/module into an angular application without having to publish it on the npm repository has been quite a challenge for me. To begin with, I decided to follow a tutorial that guided me through bui ...

Is there a way to focus on a specific iteration of the ngFor loop in Angular 9 using jQuery?

I'm working on a list of items inside a modal that uses *ngFor with checkboxes. The goal is to cross out the contents of an item when its checkbox is clicked. Here's the initial code using jQuery in home.component.ts: $('body').on(&apo ...

Angular Universal pre-renders routes with an empty router-outlet, ensuring fast initial page loads

After transitioning to Standalone APIs with Angular 16, I encountered a strange issue: SSR works perfectly as expected (with clientHydration()), but when attempting SSG (prerender), everything seems to crumble, and the lack of errors makes it hard to pinp ...

Improving DynamoDb Query Results with Type Hinting

In the following Typescript code, how can I specify which fields should be present in my Query Items Result? const request: DynamoDB.DocumentClient.QueryInput = { TableName: UnsubscriptionTokensRepository.TABLE_NAME, IndexName: 'TokenIndex&ap ...

What is the object pattern in Typescript?

Recently delving into TypeScript, I am eager to learn how to define an interface for the following type of object: const branch = { 'CN': { 'name': 'CN Name', 'branch': 'Chinoise', 'url& ...

Tips for maintaining alignment of components within an Angular Material tab:

I am facing an issue with keeping items aligned properly. Initially, I had a form with two Angular Material lists placed side by side, each occupying 6 units and it looked good. However, when I tried to enclose these two lists within a material tab, they e ...

Angular 2 has its own version of $q.when called RxJs

Back in the AngularJS 1.* days, I used to have this code snippet to refresh the auth-token: ... if (!refreshTokenInProgress) { refreshTokenInProgress = AuthService.refreshToken(); } $q.when(refreshTokenInProgress, function () { refreshTokenInProgre ...