I have a problem with typescript inheritance and property reference in Angular HTML template and couldn't solve it for a long time. (if it's question duplication, sorry for that, I couldn't find question like this).
So I have a parent interface, let it call DummyParent with some properties.
export interface DummyParent {
dummy1?: string;
dummy2?: number;
}
And I have two children of this interface.
export interface DummyChild1 extends DummyParent {
foo1?: string;
bar1: number;
}
export interface DummyChild2 extends DummyParent {
foo2?: string;
bar2: number;
}
And I have an Angular component, which get an input and it's type can be a copy of all of these interfaces.
@Input() dummy!: DummyParent | DummyChild1 | DummyChild2;
But when I have a reference in HTML template for a DummyChild property, I got an error. For example:
<ng-container *ngIf="dummy.foo1"></ng-container>
Error: Property 'foo1' does not exist on type 'DummyParent'.
Based on this error, seems that dummy property is just a DummyParent object, and I can't reference as a DummyChild1 or DummyChild2 object. My question is that, how should I instantiate @Input() dummy to be a typeof DummyParent OR DummyChild1 OR DummyChild2. I know that I can solve the problem with using object type 'any' or casting object in HTML template like this <ng-container *ngIf="$any(dummy).foo1"> but i try to avoid using these solutions. Thanks a lot for any answers.