Search code examples
arraysangulartypescriptnativescriptinjectable

Angular 2: How to return objects belonging to multiple classes extending superclass in one array?


I am trying to create a service in Angular 2-Native Script app that defines an array of news items, and has several methods that operates on the same data. These news items can be of different types, e.g. Big , small, etc each of which may have different parameters .

I have defined the interface and the service as below.

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;
}
}

I am getting an error as follows:

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

How can I define the array such that it is assignable to News Items?


Solution

  • Just cast your object explicitly 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" }
    ]