2

I've just stumbled upon the following case.

Let's say we've created 2 different Interfaces, ie:

export interface bikeDetails {
  brand: string;
  wheels: number;
}

export interface carDetails {
  brand: string;
  wheels: number;
  engines: number;
}

And now in a Component.ts a Property can be of one of both Data Types:

export class MultiComponent {
 ...
 isCar: boolean;
 elementDetails: bikeDetails | carDetails;
 ...
}

When attempting to access the "engine" property of carDetails...

<div *ngIf="isCar && elementDetails">
   <h5>{{elementDetails.engines}}</h5>
</div>

...The Binding is marked in red telling me: "Identifier 'engine' is not defined. '' does not contain such a member Angular"

If I try to bind to a common property, as, ie the "brand" property, the Error is gone:

 <div *ngIf="isCar && elementDetails">
    <h5>{{elementDetails.wheels}}</h5>
 </div>

As soon as I remove the "bikeDetails" dataType from "elementDetails", the error obviously disappears.

I've tried to use the "Safe" (?) operator, but again it doesn't seem to fix it.

So, how should I bind correctly to a non-common property existing in one of the Data Types the Object could be at that particular time ?

1 Answer 1

1

You may suppress the error message by casting elementDetails to the any type in your template:

<div *ngIf="isCar && elementDetails">
   <h5>{{$any(elementDetails).engines}}</h5>
</div>

Source: https://angular.io/guide/aot-compiler#disabling-type-checking-using-any

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.