Consider a scenario where we have a class A
and its subclass B
. The goal is to assign an array of instances of class B
to an array of instances of class A
. While this works with normal arrays, the same operation fails when using ko.ObservableArray
.
import ko from "knockout";
class A {};
class B extends A {b = 1};
const a: A = new B(); // This operation is fine
const aArr: A[] = [] as B[]; // This operation is fine
// PROBLEM OCCURS ON THE LAST LINE!
const aObs: ko.ObservableArray<A> = ko.observableArray() as ko.ObservableArray<B>;
The issue arises in the last line where the compiler flags an error:
Type 'ObservableArray<B>' is not assignable to type 'ObservableArray<A>'.
Types of parameters 'value' and 'value' are incompatible.
Type 'A[] | null | undefined' is not assignable to type 'B[] | null | undefined'.
Type 'A[]' is not assignable to type 'B[]'.
Type 'A' is not assignable to type 'B'.
It is important to note that the intent here is to assign instances of class B
to class A
, not the other way around.
How can this issue be addressed?