Angular 2: Combining objects from various classes that extend a superclass into a single array

In my Angular 2-Native Script app, I am working on creating a service that manages an array of news items with different types such as Big, Small, Referral, each having unique parameters. The service will include various methods to manipulate this data.

Below, you'll find the interface and service definitions:

import { Injectable } from "@angular/core";

export interface NewsItem {
    type: "big" | "small" | "referral";
    title: string;
    text: string;
    imageUrl?: string;
}

export interface Referral extends NewsItem {
    type: "referral";
    username: string;
}

@Injectable()
export class NewsService {
    private data = [
        { type: "big", title: "This is one big item!", text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus iaculis, turpis vitae ornare accumsan, arcu tortor ultrices nunc, eu aliquam libero sapien vitae tellus.", imageUrl: "https://octodex.github.com/images/octocat-de-los-muertos.jpg" },
        { type: "small", title: "Yes, we code!", text: "Vivamus a sem eget erat feugiat hendrerit at quis massa. Nullam varius ac eros non dignissim. Fusce gravida arcu libero.", imageUrl: "https://octodex.github.com/images/baracktocat.jpg" },
        { type: "referral", title: "Yes, we code!", username:"Vasanthi Subramaniam", text: "Vivamus a sem eget erat feugiat hendrerit at quis massa. Nullam varius ac eros non dignissim. Fusce gravida arcu libero.", imageUrl: "https://octodex.github.com/images/baracktocat.jpg" }
    ]   

    private getItems(): NewsItem[] {
        let result: NewsItem[] = this.data;

        return result;
    }
}

An error message I am encountering states:

Type '({ type: string; title: string; text: string; imageUrl: string; } 
| { type: string; title: string...' is not assignable to type 'NewsItem[]'

I'm seeking guidance on how to structure the array to ensure it is compatible with News Items.

Answer №1

To ensure proper casting, explicitly convert your object to the Referral class:

private data = [ 
    { type: "big", title: "This is one big item!", text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus iaculis, turpis vitae ornare accumsan, arcu tortor ultrices nunc, eu aliquam libero sapien vitae tellus.", imageUrl: "https://octodex.github.com/images/octocat-de-los-muertos.jpg" }, 
    { type: "small", title: "Yes, we code!", text: "Vivamus a sem eget erat feugiat hendrerit at quis massa. Nullam varius ac eros non dignissim. Fusce gravida arcu libero.", imageUrl: "https://octodex.github.com/images/baracktocat.jpg" },
    <Referral>{ type: "referral", title: "Yes, we code!", username:"Vasanthi Subramaniam", text: "Vivamus a sem eget erat feugiat hendrerit at quis massa. Nullam varius ac eros non dignissim. Fusce gravida arcu libero.", imageUrl: "https://octodex.github.com/images/baracktocat.jpg" }
]

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

Implementing CSS styles according to user preferences. Switching between dark mode and light mode based on subscription

Is there a way to dynamically change CSS property values based on user interaction, such as toggling between dark mode and light mode? I am currently exploring the option of setting up a subscription to track these changes, but I want to know how I can act ...

Ways to make a chosen row stand out in an *ngFor loop?

Struggling to find a solution within Angular2 for setting a css class when selecting a row. I want to achieve this without relying on jQuery. <table class="table table-bordered table-condensed table-hover"> <thead> <tr> ...

When hosting on render.com, the session data is not retained when redirecting to other routes

My login API checks if the user has a saved cookie in MongoDB and saves the value into req.session using the req.session.save() method. Afterward, it redirects to another route to create a response and send the client session data to be used. This function ...

What is the best way to dynamically disable choices in mat-select depending on the option chosen?

I was recently working on a project that involved using mat-select elements. In this project, I encountered a specific requirement where I needed to achieve the following two tasks: When the 'all' option is selected in either of the mat-select e ...

What is the best way to retrieve both the checked and unchecked values from a collection of checkboxes?

Check Out This live Example: I am in the process of creating a list of checkboxes with various data objects: data = [ { Key: "class_id", displayName: "Section ID", enabled: true }, { Key: "room_l4", displayName: "Location", enabled: false }, { Key: "se ...

Eliminating the most recent entry from the dropdown menu

Currently, I am exploring angular drag and drop functionality in my project. Here is the code snippet that I am using: Link to Code In the implementation, whenever an item is dropped, it automatically goes to the end of the "done" list. What I am looking ...

Can someone explain how to create a Function type in Typescript that enforces specific parameters?

Encountering an issue with combineReducers not being strict enough raises uncertainty about how to approach it: interface Action { type: any; } type Reducer<S> = (state: S, action: Action) => S; const reducer: Reducer<string> = (state: ...

Angular 7: Unable to connect with 'messages' because it is not recognized as a valid attribute of 'message-list'

Currently, I am embarking on an Angular journey to develop a hobby chat project using Angular 7 for educational purposes. My main hurdle lies in comprehending modules and components, which has led me to encounter a certain issue. The Challenge In the tut ...

What steps can be taken to troubleshoot a TypeScript-powered Node.js application running in WebStorm?

Seeking advice on debugging a node.js application utilizing TypeScript within WebStorm - any tips? ...

Using Typescript to assign a custom object to any object is a powerful feature

I am attempting to organize table data by utilizing the code found at https://github.com/chuvikovd/multi-column-sort. However, I am unsure of how to pass a custom object to the SortArray[T] object. The structure of my custom object is as follows: const ob ...

Issue encountered with Firebase JS SDK: firebase.d.ts file is missing which leads to a Typescript error when trying to

I'm currently working on an Ionic project with AngularFire. I encountered a typescript error when trying to run ionic cordova build --prod --release android. typescript error '/home/sebinbenjamin/workspace/myapp/node_modules/firebase/firebase. ...

Encountering problem with React Typescript fetching data from Spring Data REST API: the error message "Property '_embedded' does not exist" is being displayed

I am currently working on a React application that utilizes Typescript to fetch data from a Spring Data REST API (JPA repositories). When I make a specific request like "GET http://localhost:8080/notifications/1" with an ID, my JSON response does not pose ...

What is the best way to transfer a property-handling function to a container?

One of the main classes in my codebase is the ParentComponent export class ParentComponent extends React.Component<IParentComponentProps, any> { constructor(props: IParentComponent Props) { super(props); this.state = { shouldResetFoc ...

What could be causing my Ionic button to not initialize in the expected state while using ngIf with a boolean property connected to an Ionic checkbox?

I'm currently in the process of setting up a list of ingredients with checkboxes and conditional buttons, but I'm facing some challenges with the default state. Ideally, I only want the button to be visible when the checkbox is unchecked so that ...

A guide on organizing a 2D array with the bubble sort method

I am struggling with sorting a 2D array in descending order by row using bubble sort based on the last column. The data needs to be organized in descending order, but only according to the values in the last column. 6814.00 85.00 86.00 92 ...

Angular Material Slide-Toggle Takes Too Long to React

In my project, I am facing an issue with a control panel that contains an Angular Mat-Slide-Toggle element. Here is the code snippet: <mat-slide-toggle (change)="onQAStateDisplayChanged($event)">Display QA Status</mat-slide-toggle> When the c ...

Is there anyone available to offer me some assistance?

I am currently working on organizing data into three categories: full history, sent, and received. I am using a useState hook and have already set it up, but I am unsure where to implement the first variable. As a result, all transactions are being display ...

Creating components through the command line while managing multiple projects using Angular CLI 6

Currently, I am utilizing the most recent Angular CLI version (v6). Within my codebase resides a collection of applications housed within the projects directory. My objective is to create and organize various modules and components within these projects v ...

Tips for ensuring that functions can pass arguments with uniform overloads

I need to create a function that passes its arguments to another function, both with the same overloads. function original (a: number): boolean; function original (a: string, b: string): boolean; function original (a: number | string, b?: string): boolean ...

Unpacking Constructor with visible arguments

In my constructor, I utilize destructuring to simplify the parameters needed to create an object with default values. export class PageConfig { constructor({ isSliding = false }: { isSliding?: boolean; getList: (pagingInfo: PagingInfo) =&g ...