Leveraging interfaces with the logical OR operator

Imagine a scenario where we have a slider component with an Input that can accept either Products or Teasers.

public productsWithTeasers: (Product | Teaser)[];

When attempting to iterate through this array, an error is thrown in VS Code.

<div *ngFor="let product of productsWithTeasers"> {{ product.externalId }}</div>

Identifier 'externalId' is not defined. '<anonymous>' does not contain such a memberAngular

What is the correct approach to solving this issue?

Please note that the two objects are not alike, so using extend in interfaces is not desired in this case.

Answer №1

Consider enhancing the types within your productsWithTeasers. This adjustment resolved the issues I encountered in my VS Code.

productsWithTeasers: (Product | Teaser)[] | Product[] | Teaser[]
;

By defining it this way, the array can consist of a combination of Teasers and Products, or exclusively Teasers or Products.

For instance, here is a simple illustration: https://stackblitz.com/edit/angular-afcby5

html:

<div *ngFor="let prod of products">
  {{prod?.myProdAttribute}}
</div>

component:

@Component({
  selector: 'button-overview-example',
  templateUrl: 'button-overview-example.html',
  styleUrls: ['button-overview-example.css'],
})
export class ButtonOverviewExample {
  products: (Product | Teaser)[] | Product[] | Teaser[] = [{myProdAttribute: 'asd'},{myTeaserAttribute: 'fgdfg'}];
}

export class Product {
  myProdAttribute: string;
}

export class Teaser {
  myTeaserAttribute: string;
}

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 PreloadAllModules feature in Angular is failing to load lazyloaded modules

I have successfully incorporated lazy loading for my modules Products and Customers, allowing me to view the chunks when I access their respective routes. Now, I am aiming to make the above modules preload. Adding the following line should accomplish this ...

Is it possible to turn off Angular CLI ng build linting for a specific directory?

I am facing an issue with a specific directory in my project template that I want to exclude from linting. Despite excluding it in both tsconfig and eslint, running eslint works fine but when using ng build, the directory is still included in linting and e ...

Is there a way to delegate properties in Angular 2+ similar to React?

When working with React, I have found it convenient to pass props down dynamically using the spread operator: function SomeComponent(props) { const {takeOutProp, ...restOfProps} = props; return <div {...restOfProps}/>; } Now, I am curious how I ...

Angular 6 is experiencing an issue with the functionality of the file toggle JS

Currently, I am utilizing the file toggle.js within the Urban theme. In the HTML chatbox, using the img, the file toggle.js is hardcoded and is functioning properly. However, when implementing code in Angular 6, the toggle.js is not functioning as expecte ...

Can you verify that the client's date and time locale are accurate in JavaScript before proceeding with processing?

For my application, I am seeking the current locale datetime. However, before retrieving the date, it is crucial to verify that the local date and time are accurate. If the user has adjusted the date and time incorrectly on their machine, I must prompt a ...

Challenges with Angular observables

Struggling to make observables work has been quite the challenge for me lately. My code now resembles a chaotic battleground rather than the organized structure it once was. The dreaded "ERROR TypeError: Cannot read property 'map' of undefined" ...

Is Angular 2 Really Suitable for Multi-Page Applications?

I am currently working on a multi-page app using Angular2 and have noticed that the load times are slower than desired when in development mode. While searching for solutions, I came across a thread on stackoverflow that explains how to set up Angular2 fo ...

Typescript fails to properly identify the yield keyword within a generator function or generator body

Here is the code for my generator function: function* generatorFunction(input: number[]): IterableIterator<number> { input.forEach((num) => { yield num; }); An error occurred during linting: A 'yield' expression is only allowed ...

What is the reason behind the possibility of assigning the exported class to a variable within Ionic 2?

The code snippet below can be found in settings.ts: @Component({ selector: 'page-settings', templateUrl: 'settings.html' }) export class SettingsPage { } } Similarly, in the app.component.ts file, we are able to assign the Clas ...

Expanding a component using the identical selector in Angular 2 / Angular-CLI

We are leveraging Angular to create a sleek component-based frontend for our primary application. Our various clients often request minor customizations to these core components. To maintain the integrity of our core code, we plan to store it in NPM packag ...

Using TypeScript to work with asynchronous child_process.exec operations

Having trouble implementing a child_process.exec call with TypeScript and finding error handling to be quite challenging. Here's the basic idea of what I'm attempting: import { promisify } from "util"; import { exec, ExecException } fr ...

Leveraging Vue mixin within a @Component

After implementing the vue-property-decorator package, I encountered an issue when trying to use a mixin method inside the beforeRouteEnter hook. Here is what I initially tried: import { Component, Mixins } from 'vue-property-decorator'; import ...

Using a function as an argument to handle the onClick event

I have a function that generates a React.ReactElement object. I need to provide this function with another function that will be triggered by an onClick event on a button. This is how I call the main function: this._createInjurySection1Drawer([{innerDra ...

Why are the class variables in my Angular service not being stored properly in the injected class?

When I console.log ("My ID is:") in the constructor, it prints out the correct ID generated by the server. However, in getServerNotificationToken() function, this.userID is returned as 'undefined' to the server and also prints as such. I am puzz ...

Unable to retrieve the key value from a child object in Angular 2 when working with JSON Data

Currently, I am using Angular and attempting to extract data from the child object's key value. Here is the JSON data provided: "other_lessons": [ { "id": 290, "name": "Christmas Test #290", "course": { "id": ...

Error with TypeScript Compiler in Angular 2

Currently, I am facing an issue while trying to run tsc in my Angular 2 application directory. The error message I receive is: Error TS5023: Unknown compiler option 'moduleResolution'. This issue seems to be hindering the startup process, as ts ...

Azure Function (.NET 7, v4) encountering Cross-Origin Resource Sharing problem

I am experiencing a CORS problem with my Azure function written in C# using .NET 7. It is being called from my Angular application. Interestingly, the same function works fine when called from Postman with the same request body as the Angular application. ...

Tips for effectively utilizing TypeORM transactions

I'm encountering an issue with transactions in TypeORM. Here's a snippet of the code causing me trouble: const someFunction = async () => { try { await this.entityManager.transaction(async (manager) => { //some opera ...

How to avoid property sharing in Angular recursive components

I am currently working on a recursive component that generates a tree structure with collapsible functionality. However, I am facing an issue where the state variable active is being shared among child components. Is there a way to prevent this from happen ...

What is the best way to download a file with a specific name using Angular and TypeScript?

Greetings! Below is a snippet of code from my Angular component: this.messageHistoryService.getMessageHistoriesCSV1(msgHistoryRequest).subscribe( (data) => { console.log(data.messageHistoryBytes); let file = new Blob( [data.messageHistoryBytes ...