Troubles with Typescript typings when including an empty object in an array with specific typings

, I am facing a dilemma with displaying houses in a cart. Each house has an image, but since they load asynchronously, I need to show empty cards until the data is fetched. Initially, I added empty objects to the array representing the houses, which worked well until I introduced typing through Typescript. Removing typing would be a quick fix, but not ideal. Making all properties optional is also not recommended. So my question is, should I create mock objects with the necessary properties (which seems like a lot of work), or is there a better way to handle this situation? Here is a snippet of the code showcasing how I preload the empty cards and then populate them with actual data once it's retrieved:
houses: House[] = [{}, {}, {}, {}, {}];

ngOnInit(): void {
  this.housesService.getGreatHouses().subscribe(houses => {
    if (houses && houses.length > 0) {
      this.houses = houses;
    }
  });
}

Answer №1

Option 1:

// Declaring an array of optional House properties using Partial<>
houses: Partial<House>[] = [{}, {}, {}, {}, {}];

ngOnInit(): void {
  this.housesService.getGreatHouses().subscribe(houses => {
    // Utilizing TypeScript >= 3.7 for the safe navigation operator `?.`
    houses?.forEach((house, index) => {
       Object.assign(this.houses[index], house);
    });
  });
}

Option 2:

// Initializing House properties with null values
houses: House[] = [{ id: null, picture: null, ... }, { id: null, picture: null, ... },{ id: null, picture: null, ... }, ...];

// Assigning values similarly to Option 1

Consider converting House into a class (Model) instead of an interface or type to avoid manual scaffolding and benefit from instance features.

Option 2 aligns with @Eldar's suggestion in the comments, providing a cleaner and potentially more efficient solution especially at scale.

What makes Option 2 cleaner and potentially more efficient at scale?

Modifying object properties or removing them (delete obj.property) can hinder JavaScript interpreters' ability to optimize code execution at runtime. Using explicit structures that remain consistent can improve code readability and debuggability, making it easier to maintain in the long run.

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

Having trouble with errors when adding onClick prop conditionally in React and TypeScript

I need to dynamically add an onClick function to my TypeScript React component conditionally: <div onClick={(!disabled && onClick) ?? undefined}>{children}</div> However, I encounter the following error message: Type 'false | (() ...

Exploring the File Selection Dialog in Node.js with TypeScript

Is it possible to display a file dialog in a Node.js TypeScript project without involving a browser or HTML? In my setup, I run the project through CMD and would like to show a box similar to this image: https://i.stack.imgur.com/nJt3h.png Any suggestio ...

Transforming JSON data into comma-delimited values (with thousands separators) using Angular 5 and ES6 syntax

Is there a more elegant method to convert a JSON response into comma-separated numbers for displaying currency purposes? Here is the code I have currently: let data = { "business":{ "trasactionTableData":[ { ...

Adding form controls to an existing form group in Angular 2 can be done by following these steps

Initially, I have created a form group in ngOnInit. However, I need to dynamically add more controls to this existing form group when a specific control is clicked. These additional controls are obtained from another API call made in ngOnInit. The image be ...

Guide to importing a class property from one file to another - Using Vue with Typescript

Here is the code from the src/middlewares/auth.ts file: import { Vue } from 'vue-property-decorator' export default class AuthGuard extends Vue { public guest(to: any, from: any, next: any): void { if (this.$store.state.authenticated) { ...

Transform the string property extracted from the API into a JSON object

When making a request to an API, the data returned to the front end is in the following format: { name: 'Fred', data: [{'name': '"10\\" x 45\\" Nice Shirts (2-pack)"', 'price' ...

Using AngularJS with CDN: A beginner's guide

If I need to create an app using AngularJS with Cordova in Visual Studio, do I need anything else besides the Google CDN for AngularJS? <!doctype html> <html ng-app> <head> <title>My Angular App</title> <script s ...

Prohibit communication by any means

Let's take a look at the following function overloads: function f(key: undefined); function f(key: string | undefined, value: object | undefined); I want to allow calls with a single explicit undefined argument f(undefined), but require two argument ...

Running Angular/Rxjs store (ngrx) calls synchronously

After fetching 2 items from my store using ngrx, I need both requests to complete before taking further action. Here's an example of what I'm trying to achieve: const item1$: Observable<Item> = this._store$.select( ItemStoreSelectors.sele ...

Utilizing a feature module imported from a separate Angular4 project

I have a question about setting up an Angular 4 project. Can feature modules be loaded from another Angular 4 project? I am currently attempting to maintain separate project repositories and dynamically load feature modules into the main project. This wa ...

Avoid altering the background color when adjusting the scale view on an apex chart due to changes in graph data

I have developed Apexchart components for line charts that come with a date filter picker feature. This chart is interactive and changes dynamically based on the series data provided. function DisplayChart({ series, xaxis }: { series: any; xaxis?: any }) ...

Calculating the total number of rows that are currently selected in the ag-grid

I am struggling to get an accurate count of the selected rows in my grid. It seems like onRowClicked or onRowSelected events are triggered before the row I click is actually selected. Is there a way to accurately count the number of selected rows when a r ...

Issue with radio button validation not being triggered upon form submission

I am encountering an issue with validating a radio button in a form. Despite my efforts, I am able to proceed to the next page without selecting a radio button option. However, the validation for the email address field is working correctly. Below is the r ...

How can I use Angular2 to ensure that a child component automatically updates when there is a change in the parent's property?

After reviewing the components provided below, it appears that the parent's property updates correctly, but unfortunately, the changes are not reflected in the child component. What steps should I take to ensure that the child component accurately ref ...

Add flexible templates into List element in Ionic version 3

My Progress Being a newcomer to ionic, I successfully created a List component in ionic 3 that retrieves JSON data from the server and displays it as a list layout on specified pages using a list selector. Objective I am looking to showcase various list ...

Checking all checkboxes in a list using Angular 5: A simple guide

I have a list that includes a checkbox for each item, and I want to confirm if all of them are checked off. This is the HTML code snippet: <ul class="ingredient-list" > <li class="btn-list" *ngFor="let ingredient of recipe.ingredients"> ...

A step-by-step guide on injecting a model within the root app module of a Nest JS application

Hello, I encountered an error in my Nest app and here is a screenshot of the error: https://i.stack.imgur.com/zY1io.png Below is the code snippet for the AppModule: @Module({ imports: [AppModule,CrudModule,MongooseModule.forRoot("mongodb://localhost:2 ...

Angular Project: Exploring Classes and Interfaces with and without the Export Keyword

Currently, I am delving into the world of Angular. I have taken up a video course and also referred to a PDF book, but I find myself perplexed when it comes to understanding the usage of the "export" keyword... The PDF course focuses on Angular 5 and util ...

Angular 8's array verification feature lacks the ability to recognize preexisting elements

I've been trying to add and delete items in an array when a user selects or deselects the same item. However, it appears that either my array is not working properly or there is a bug in my code causing it to fail. <div class="grp-input"> ...

Using Generic Types in TypeScript for Conditional Logic

To better illustrate my goal, I will use code: Let's start with two classes: Shoe and Dress class Shoe { constructor(public size: number){} } class Dress { constructor(public style: string){} } I need a generic box that can hold either a ...