I am using a variable in my Angular project that is defined as following:
item: Interface1|Interface2
. Both interfaces have the property "section", but it is defined differently as following.
Interface1:
section: string;
Interface2:
section: {
property1: string;
property2: string;
};
Now when I am rendering, I am calling the following code:
<h2 *ngIf="check">
{{ item.section.property1}
</h2>
<h2 *ngIf="!check">
{{ item.section}
</h2>
check is true when the element is of the type Interface2 and should therefore act as a guard from my understanding. I thought since the first heading should not be rendered, it shouldn’t matter that item does not have property1 in that case. I get an error though, that says "Property ‘property1’ does not exist on type ‘string’".
What am I doing wrong?
I have tried putting the *ngIf in an ng-template around the heading, since from my understanding it shouldn’t be added to the DOM then, but that resulted in the same error.
I then tried defining the item as followed: item: Interface1&Interface2
, which removed the error, but when trying to render the second heading, it displayed [object Object] instead of the string.
2
Answers
I fixed it now, what worked in the end was defining item as:
I had another bug in my code that was causing the [object Object] error.
Don’t do
Interface1 & Interface2
, you should doInterface1 | Interface2
.Check another time how you define your
check
variable because I see that your prolem is on different behavior.I tried to reproduce your case so here is code: https://angular-b2pk9z.stackblitz.io