I am struggling to implement polymorphism in my Angular 4 project. Unfortunately, I am encountering an error when trying to access a member in a child class. The error message thrown by the compiler 'ng build --prod' is: /$$_gendir/app/app.component.ngfactory.ts (23,38): Property 'bark' does not exist on type 'Animal'.
Does anyone have any insights on how to resolve this issue? Thank you.
app.component.html:
<div *ngIf="isDog(family)">
<!-- Property 'bark' does not exist on type 'Animal'. -->
<h4>{{family.bark}}</h4>
<!-- Parser Error: Missing expected ) at column 9 -->
<h4>{{(family as Dog).bark}}</h4>
</div>
<div *ngIf="isCat(family)">
...
</div>
app.component.ts:
import {Component, OnInit} from '@angular/core';
export class Animal {}
export class Dog extends Animal {
bark: string;
}
export class Cat extends Animal {
meow: string;
}
const sampleData: Animal = { 'bark': 'wof'} as Dog;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
family: Animal;
ngOnInit() {
this.family = sampleData;
}
}