skip to Main Content

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


  1. Chosen as BEST ANSWER

    I fixed it now, what worked in the end was defining item as:

    item: Interface1&Interface2
    

    I had another bug in my code that was causing the [object Object] error.


  2. Don’t do Interface1 & Interface2, you should do Interface1 | 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search