Error in Typescript regarding inheritance and the usage of static methods in classes

I encountered an issue with TypeScript while compiling the code snippet below:

class A {
  public static then() {
    return this;
  }
}

class B extends A {
  public static shouldWorks() { return 42; }
}

console.log(B.then().shouldWorks());

When I compile the script, the compiler throws the following error:

error TS2339: Property 'shouldWorks' does not exist on type 'typeof A'.

However, when I run the compiled script, it works fine!

Why is this happening?

Answer №1

In static methods, the concept of polymorphism does not apply to this. In this case, this will simply be typeof A when the class is returned from the method then, meaning that methods added in class B will not affect this class.

To achieve a form of polymorphic behavior with this, you can specify a type for the this parameter. The type of this will then be inferred as a type parameter based on the calling context:

class A {
    public static then<TThis extends new (...a: any[]) => A>(this: TThis) {
        return this;
    }
}

class B extends A {
    public static shouldWorks() { return 42; }
}

console.log(B.then().shouldWorks()); 

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

Exploring the DynamoDB List Data Type

Currently, I am working on an angular 8 application where I have chosen to store JSON data in a list data type within DynamoDB. Inserting records and querying the table for data has been smooth sailing so far. However, I have run into some challenges when ...

Deriving variable function parameters as object or tuple type in TypeScript

Searching for a similar type structure: type ArgsType<F extends Function> = ... which translates to ArgsType<(n: number, s: string)=>void> will result in [number, string] or {n: number, s: string} Following one of the provided solu ...

Is a package.json file missing dependencies?

Curious about the meaning of peerDependencies, I examined the contents of this package.json file. It relates to a library project that is distributed elsewhere. { "name": "...", "version": "...", "description": "...", "author": "...", ...

Exploring ways to traverse through Map values

My app initially displays a grid of cells that I would like to fill in with data. Here is the initial view: https://i.sstatic.net/AgI16.png -> As the app runs, each rider's score will be updated dynamically like this: https://i.sstatic.net/HOPoN ...

What is the best way to incorporate dynamic infographics into an ionic app?

Looking to design unique infographics for my ionic app, similar to the ones seen here: Any recommendations on tools or strategies for creating these infographics? ...

How can I rectify the issue in TypeScript where the error "not all code paths return a value" occurs?

While developing an application, I encountered an error that says: "not all code paths return a value". The error is specifically in the function named addValues, indicating that the function must return "Obj[] | undefined". Here is the code snippet in qu ...

Similar to [JsonPropertyName] in C#, but for TypeScript

Need help deserializing JSON response into a class defined in Angular. Let's use the example class below: export class ChatHubInfo { hubUrl: string = undefined! accessToken: string = undefined! } However, the JSON response is structured different ...

What is the process of invoking an external JavaScript function in Angular 5?

I recently downloaded a theme from this source. I need to specify script and CSS in the index.html file. The body section of index.html looks like this: <body> <app-root></app-root> <script type="text/javascript" src="./assets/js ...

How can one correctly cast or convert an array of objects to the interface that extends the objects' parent interface in Typescript?

Question: How can I optimize the usage of method sendItemIdsOverBroadcastChannel to reduce message size? interface IItemId { id: number; classId: number; } interface IItem extends IItemId { longString: string; anotherLongString: string } inte ...

Angular2's ngControl is unable to retrieve default values

I have been working on a form using Angular 2 (RC.3) and noticed that the `ngForm` directive is not recognizing default values set with the `value` attribute. // app.component.html <form (ngSubmit)="onSubmit(editForm.value)" #editForm="ngForm"> &l ...

Issues arise when attempting to assign GraphQL types, generics, and NestJS Type<> as they are not interchangeable with Type<&

I've been attempting to use this definition: import { GraphQLScalarType } from 'graphql'; import { Type } from '@nestjs/common'; export function createFilterClass<T extends typeof GraphQLScalarType>( FilterType: Type&l ...

Is there a way to track all Angular form controls that have switched between being enabled and disabled?

Summary: When a FormGroup contains a nested FormControl that changes from disabled to enabled or vice versa, the FormGroup is not marked as dirty. Details: How can you identify all form controls within a FormGroup that have switched between being enabled ...

What is the best way to navigate to the next input field upon pressing the tab key in an Angular table?

In the Angular table, how can I make the cursor move to the next input field when the tab key is pressed? Essentially, when the tab key is pressed in a cell, I want the cursor to move to the next cell from left to right. For example, in the screenshot belo ...

The unholy trinity of RxJS, Typescript, and the infamous 'Type Mismatch' error message

It's clear that I'm overlooking something obvious. The pseudo code below works perfectly in production, but my IDE (IntelliJ IDEA) is throwing an error that I can't solve. I can suppress it with noinspection TypeScriptValidateTypes, but I re ...

Endlessly calling a function binding to a property

I've come across a very peculiar issue in my Angular application. Imagine I have a simple example.component.ts @Component({ moduleId: module.id.toString(), selector: 'example', templateUrl: 'example.component.html', ...

How can I test for equality with an array item using v-if in Vue.js?

Currently, I am facing a challenge in my Vue.js project where I need to determine if a number is equal to an element within an array. Here is the code snippet that I am working with: <div v-if="someValue != arrayElement"> // </div> I am st ...

Issue with Material Checkboxes failing to respond correctly when their 'checked' variant is applied

In my records table, each column begins with a checkbox. When a checkbox is clicked, the record's id is stored in an array using TypeScript: onCheckboxClick(id) { if (this.selectedInvoiceables.indexOf(id) > -1) { this.selectedInvoiceables.sp ...

Tips for updating the returned parameter from a function in Angular

I am currently facing an issue with the DevExtreme datasource and have already reached out to their support team for assistance. However, I can't help but wonder if I might be overlooking something simple in Angular. DevExtreme offers an AspNetData s ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...

What is the best way to pass props to a styled component (e.g., Button) in Material-UI

One of my tasks involves creating a customized button by utilizing the Button component with styled components. export const CustomButton = styled(Button)({ borderRadius: "17px", fontWeight: 300, fontSize: ".8125rem", height: &q ...