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

The import of type cannot be done within paths in tsconfig

Currently, I am tackling a server side project utilizing TypeScript. In this context, I have established various types in ooo.d.ts and configured the paths within tsconfig.json. However, upon attempting to import the specified type, an error is being displ ...

PhpStorm alerts users to potential issues with Object methods within Vue components when TypeScript is being utilized

When building Vue components with TypeScript (using the lang="ts" attribute in the script tag), there is a warning in PhpStorm (version 2021.2.2) that flags any methods from the native JavaScript Object as "Unresolved function or method". For exa ...

Leveraging Angular's catchError method to handle errors and return

One of my challenges involves a model class that represents the server response: class ServerResponse { code: number; response: string; } Whenever I make api calls, I want the response to always be of type Observable<ServerResponse>, even in ...

Remember to always call "done()" in Typescript + Mocha/Chai when dealing with async tests and hooks. Additionally, when returning a Promise, make sure it resolves correctly

It seems like I'm facing an old issue that I just can't seem to resolve, despite trying everything in my power. The error message reads: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Pro ...

What steps should I take in order to correctly implement the onChange event and retrieve the event.target.value in my

Incorporating useForm, yupResolver, and Yup for validation caused issues with the previously functioning handleChange function. The value variable doesn't log anything when console.logged, indicating a disconnect with the input field content. Addition ...

Add the onclick() functionality to a personalized Angular 4 directive

I'm facing an issue with accessing the style of a button in my directive. I want to add a margin-left property to the button using an onclick() function in the directive. However, it doesn't seem to be working. Strangely, setting the CSS from the ...

Is there an equivalent concept to Java's `Class<T>` in TypeScript which allows extracting the type of a class constructor?

I'm in need of a feature similar to the Class functionality in Java, but I've had no luck finding it. Class<T> is exactly what I require. I believe it could be named NewableFunction<T>. However, such an option does not exist. Using M ...

Identify the classification of unfamiliar items

Occasionally, you may find yourself in situations where you have to work with packages that were not designed with TypeScript in mind. For instance, I am currently using the two.js package in a React project with TypeScript strict mode enabled. It has been ...

Encountering a 401 Error while integrating Azure App Configuration within an Angular 9 Application

After implementing the library found at https://www.npmjs.com/package/@azure/app-configuration Despite following the setup instructions, I encounter a 401 error whenever I make a request using the AppConfigurationClient. The response headers indicate: ww ...

Verifying whether the filter query will produce any matches

I'm currently working with a *ngIf statement and I need to show a specific message when the condition is not met. However, I'm facing difficulties in finding a way to achieve the opposite of the filtered result. Essentially, I want to display a m ...

How can a default value be assigned to an ag-Grid filter?

Is there a way to set a default value in ag-grid filter text that is displayed to the user but not applied to the actual results? this.columnDefs = [ { headerName: this.pageData["tbm.line.list.grid.phonenumber"], field: 'tn', /*sor ...

Issue with TypeScript problemMatcher "$tsc-watch" not actively monitoring files in VSCode

I'm attempting to avoid the necessity of using watch: true in my tsconfig.json setup. Despite utilizing VSCode's tasks with the default problem matcher $tsc-watch, I am encountering an issue where tsc is not running in watch mode during the buil ...

Tips for preserving the order of Angular's rearranged list obtained from the backend

Upon opening the page, users encounter a list that can be rearranged using Angular's drag and drop feature. The issue arises when the front-end order differs from the back-end order. What is the most efficient method to maintain the order of this list ...

Comparing Angular global variables: when to use static readonly in service class versus const

Which method is the better choice? @Injectable({ providedIn: 'root' }) export class MyService { static readonly VALIDITIES = new Map<number, string>([ ... ]); ... } OR: const Validities = new Map<number, string>([ .. ...

Global registration of router directives with Angular router RC3 is required

I'm trying to avoid registering the Router_Directives for each individual component. Instead, I would like to apply it globally similar to how I did before: import { RouterConfig ,Router, ActivatedRoute, ROUTE_PROVIDERS} from '@angular/router&a ...

Challenges with React Event Listener Types

https://i.sstatic.net/cVlpr.png useEffect(() => { const handleEscClose = (e: KeyboardEvent) => { if (e.key === 'Escape') changeVisibility(); }; if (isVisible) document.addEventListener('keydown', handleEscClos ...

typescript encounters issues with union type while trying to access object properties

I'm puzzled by the errors I'm encountering in my IDE with the following code: I defined some interfaces/types interfaces/types: interface GradientColor { type: string; value: { angle: string | number; colours: string[]; }; } inte ...

The implementation of Typescript in Express does not rely on Middleware

I've encountered an issue with my Auth Middleware - it seems that the middleware isn't being called at all. Even when I intentionally throw an Error within the middleware function, nothing is printed out. For testing purposes, I only need to inv ...

When importing a React Component with styling into the pages folder, it fails to function properly

I created a component in my components directory with custom styling: // import Link from "next/link"; import {Link} from "react-scroll" export default function Navbar() { return ( <div className="fixed w-full h-[79px] fle ...

In a functional component in Typescript, what data type should be used for a parameter that accepts an array of objects?

const FormData = ({ dataArray }: object[]): JSX.Element => { console.log("Array of Objects",dataArray) //This is a large form component.... }); The dataArray contains multiple objects, how can I specify a specific type for these components ...