I have got a problem with an Input() Variable of an Angular Component. It throws a type related error on the pages template file. I have got two interfaces, one page and one component to make the error occur.
The two interfaces are Bike
and BikeMin
where Bike
extends BikeMin
(and other interfaces):
export interface Bike extends BikeRemote, BikeMin, BikeLocal {}
I have got a Component BikeFeaturePickerComponent
with an ngModel of type BikeMin
:
export class BikeFeaturePickerComponent {
@Output("bikeChange")
public bikeChange: EventEmitter<BikeMin> = new EventEmitter<BikeMin>();
@Input("bike")
public bike: BikeMin;
ngOnInit(): void {}
constructor(public featuresService: FeaturesService, public bikeInfoService: BikeInfoService) {}
}
I am using the Component BikeFeaturePickerComponent
on the Page DetailPage
which has the public property bike: Bike
.
detail.page.ts:
export class DetailPage implements OnInit {
public bike: Bike;
...
}
detail.page.html:
<app-bike-feature-picker [(bike)]="bike"></app-bike-feature-picker>
Now the error occurs on the detail.page.html. It says that I cannot assign the variable of type Bike
to a variable of type BikeMin
although Bike
has all the properties of BikeMin
. Inside of functions I can assign variables of type Bike
to parameters of type BikeMin
. But when using Input() from @angular/core I get the following error:
No errors occur at runtime (ionic serve
) either. The code can be executed despite the compiler error. Also no errors on ionic build
. Possibly the error is only caused by Visual Studio code. But how can I get rid of it?
Thankful for any advice.
CodePudding user response:
As you're using two way binding, the casting of the type is going both up and down i.e. Bike -> BikeMin
and BikeMin -> Bike
. I'm guessing it's the BikeMin -> Bike
that's causing the issue
You may need to use a union type in DetailPage
public bike: Bike | BikeMin;
CodePudding user response:
Thanks to https://stackoverflow.com/a/70011876/11063209
It works when changing the Output type to the more general type Bike
. Because the specific interface BikeMin
cannot be castet to the generel Bike
interface on the Output:
@Output("bikeChange")
public bikeChange: EventEmitter<Bike> = new EventEmitter<Bike>();
@Input("bike")
public bike: BikeMin;