What is causing the failure of this polymorphic assignment within a typed observableArray in Knockout?

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?

Answer №1

There is an issue with ObservableArray<T> as it is contravariant on the type variable T. This causes assignments to occur in reverse direction.

While you can easily assign B to A (since B extends A and no explicit declaration is needed) when placed in a covariant position:

class A { }
class B { b = 1 }

const a: A = new B();
const aArr: A[] = [] as B[];

Link to playground for demonstration

You cannot directly assign a function with arguments of these types in the same direction, only in the opposite one.

type Fn<T> = (t: T) => void

const fn1: Fn<A> = null as unknown as Fn<B> // error occurs here
const fn2: Fn<B> = null as unknown as Fn<A> // no error

Link to playground for demonstration


If you are confident that the assignment is correct and the compiler is unnecessarily restricting you, you can manually typecast it to the expected type:

import ko, { ObservableArray } from 'knockout'

class A {};
class B extends A {b = 1};

const bObs: ObservableArray<B> = ko.observableArray()
const aObs: ObservableArray<A> = bObs as unknown as ObservableArray<A>;

Link to playground for demonstration


You also have the option to globally disable contravariance checking for function arguments using --strictFunctionTypes. However, this check is usually beneficial most of the time.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a canvas that adjusts proportionally to different screen sizes

Currently, I am developing a pong game using Angular for the frontend, and the game is displayed inside an HTML canvas. Check out the HTML code below: <div style="height: 70%; width: 70%;" align="center"> <canvas id=&q ...

There were no visible outputs displayed within the table's tbody section

import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = [{"id":1,"isActive":true,"object":"Communication","previ ...

Generics in Typescript interfaces

I'm trying to grasp the meaning of T = {} within this TypeScript interface. I've searched for documentation on this usage but haven't found anything specific. How does it differ from simply using T? interface CustomProps<T = {}> { ...

Finding the index of a chosen option in Angular

Attempting to retrieve the index of the selected option from a select element using Angular. The Angular (4) and Ionic 3 frameworks are being utilized. The template structure is as follows: <ion-select [(ngModel)]="obj.city"> <ion-option ...

` Detecting initialized properties of classes using Eslint rule`

When useDefineForClassFields:true is used, the code below becomes invalid when targeting es2022: Cannot read properties of undefined (reading 'array') class Bar { array = new Array(); } class Foo { foo = this.bar.array; // Property &apo ...

Upon hovering, icons for each project name are displayed when `mouseenter` event is triggered

My issue lies with the mouseenter function. I am trying to display icons specific to the project name I hover over, but currently, it displays icons for all projects at once. I want each project hovered over to show me its respective icons Below is some c ...

What is the best way to refer to a specific argument by implication within a function type?

Is there a way to extract the name of an argument from one type and use it in another type? For example, is it possible to achieve something like this: type F_v1 = (name: number) => boolean; type A = ["name", number]; //type F_v2 = (A[0]: A[1]) => bo ...

Angular Material Table displaying real-time information

Recently, I've delved into Angular and have been experimenting with creating a dynamic table to showcase data. Currently, I have managed to get it partially working with static data. I drew inspiration from this particular example: https://stackblit ...

Opening and closing a default Bootstrap modal in Angular 2

Instead of using angular2-bootstrap or ng2-bs3-modal as recommended in the discussions on Angular 2 Bootstrap Modal and Angular 2.0 and Modal Dialog, I want to explore other options. I understand how the Bootstrap modal opens and closes: The display pro ...

What are some key indicators in the source code that differentiate TypeScript from JavaScript?

Reviewing some code on Github, I am looking for ways to quickly determine whether the script is written in JavaScript or TypeScript. Are there any simple tips or hints that can help with this? For instance, when examining an array declaration like the on ...

Is it possible to associate a generic TypeScript type with another type by utilizing its generic parameters?

I am faced with a situation where I have a family of APIs consisting of various related generic types (along with associated constraints). To illustrate this, I have crafted an example using familiar types as placeholders for better understanding. As I wo ...

Creating an Object Type from a String Union Type in TypeScript

How can I go about implementing this? type ActionNames = 'init' | 'reset'; type UnionToObj<U> = {/* SOLUTION NEEDED HERE */} type Result = UnionToObj<ActionNames>; // Expected type for Result: `{ init: any, reset: any }` ...

What purpose does the # symbol serve in Angular when interpolating values?

Here is an example provided from the following link: https://angular.io/guide/lifecycle-hooks export class PeekABoo implements OnInit { constructor(private logger: LoggerService) { } // Implementing OnInit's `ngOnInit` method ngOnInit() { this ...

Versatile Typescript options

Is it possible to enforce a value to be within a list using TypeScript with enums? Can this be achieved with TypeScript type definitions? enum Friend { JOHN, SALLY, PAUL, } type MyFriends = { friends: Friend[], bestFriend: <> //How ca ...

What steps should I take to troubleshoot this Angular issue within a Visual Studio 2022 project that utilizes the Standalone Angular template?

After going through this tutorial and meticulously following each step, I encountered an error when trying to run the application: https://i.sstatic.net/EvYgg.jpg Can anyone advise on how to resolve this issue? I'm facing a similar error while attem ...

Checking for Object Equality in TypeScript

I'm working on a TypeScript vector library and encountered my first failed test. The issue revolves around object equality in TypeScript/JavaScript, and despite searching through TypeScript's official documentation (http://www.typescriptlang.org ...

What about combining a fat arrow function with a nested decorator?

Trying to implement a fat arrow function with a nestjs decorator in a controller. Can it be done in the following way : @Controller() export class AppController { @Get() findAll = (): string => 'This is coming from a fat arrow !'; } Wh ...

Issues with select options not functioning correctly in knockout framework

Currently, I am engaged in a project where data is being retrieved from an API. The main task at hand is to create a dropdown list using select binding. In order to do so, I have defined an observable object to hold the selected value within my data model. ...

Discover the power of TypeScript's dynamic type inference in functions

Below is a function that selects a random item from an array: const randomFromArray = (array: unknown[]) => { return array[randomNumberFromRange(0, array.length - 1)]; }; My query pertains to dynamically typing this input instead of resorting to u ...

Implement dynamic validation in Angular 4 based on specific conditions

I am looking to implement Angular 4 validation dynamically based on specific conditions within a Reactive form. Here is the scenario: There is a radio button with options: A: yes B: no If the user selects "yes", a textbox (formControlName="your_name") wil ...