Using TypeScript to define a variable as a subclass of an abstract class

Imagine

abstract class A {
  protected abstract f(): void;
}

class B extends A {
  public f() { return 'B'; }
}

class C extends A {
  public f() { return 'C'; }
}

If you want an array that contains B and C, you can achieve it by:

let arr: Array<B | C> = [/* lots of objects */];
arr.forEach(item => item.f());

But if you want to make Array<B | C> more flexible and general, so it would be Array</*descendant of A*/>.

Any suggestions on how to approach this?

Answer №1

To access the array item, simply use A. Make sure that f is public if you want to call it on derived types outside of the class. There are no restrictions on abstract members being protected:

abstract class A {
    public abstract f(): string;
}

class B extends A {
    public f() { return 'B'; }
}

class C extends A {
    public f() { return 'C'; }
}

let arr: Array<A> = [/* many objects */];
arr.forEach(item => item.f());

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

Dealing with "Cannot find name" errors in Typescript when working with React components

I'm currently in the process of transitioning my React code to TypeScript, and I've encountered numerous challenges. One recurring issue is the "Cannot find name" errors that pop up when converting my .js files to .ts files. Let's take a lo ...

Determine the sum of exported identifiers based on ESLint rules

Currently, I am facing a requirement in my JavaScript/TypeScript monorepo to ensure that each library maintains a minimal amount of exported identifiers. Is there any existing eslint rule or package available that can keep track of the total number of exp ...

Generate user-customized UI components from uploaded templates in real-time

Summary: Seeking a solution to dynamically generate UI pages using user-provided templates that can be utilized for both front-end and back-end development across various use cases. Ensuring the summary is at the top, I am uncertain if this question has b ...

Storing an arrayBuffer in a MySQL database using blob and xdevapi in Typescript can be accomplished by converting

I need to save various user files (mostly images) that are uploaded via a HTML input field into a MySQL database. My goal is to store the arrayBuffer of these files in a MySQL blob using @mysql/xdevapi. Current setup: Using Angular with Electronjs MySQL ...

Use the rowTemplate in a Kendo grid without replacing the existing one

I am currently utilizing Angular 1.4 with TypeScript and Kendo UI (employing angular directives). My goal is to create a RowTemplate for each row that dynamically changes the color based on a specific property of the item. While I am aware of jQuery solu ...

Using TypeScript to pass parameter in a chained function

When using node.js, I am calling a script with `exec` from the `child_process` module. In the closed state, I need to verify if there was any error so that I can handle it properly. However, I am facing an issue where I cannot access the `error` parameter ...

TypeScript types for employing Queries within React Query

Currently, I have this setup: // useMyList hook: const allQueries = myList.map((myData) => { return { queryKey: ['myquerykey'], queryFn: myQueryFn } } return useQueries(buildQuery) Within my component, it looks like this: const ...

Automating a login prompt with dual inputs using WebdriverIO: A step-by-step guide

I'm having trouble automating the login prompt as shown in the attached image. I've attempted to fill in both fields using WebdriverIO but so far have been unsuccessful. I explored using alert methods like browser.sendAlertText(), but none of the ...

Using type declaration, how can one create an arrow function?

I've been working on converting the following JavaScript code to TypeScript: users.map( item => ( { name: item.name, email: item.email, ...item.user } )); The structure of users looks like this: users = [ { name: &quo ...

Incorporating a class element within an Angular 2 directive

When working with Angular 2 directives, one way to add an element is by using the following code: this._renderer.createElement(this._el.nativeElement.parentNode, 'div'); After adding the element, how can I set its class and keep a reference to ...

Activate expansive pop-up windows with primeng's dynamic dialog feature

In my Angular web application, I am using the PrimeNg modal extension to display modal popups. I have successfully passed a component to the modal service with the following code: const ref = this.dialogService.open(LogsComponent, { data: { ...

In Angular-Cli, the variables @Input and @Output are consistently null until they are assigned

Individuals' internal values are printed without any problems, but those obtained using @Input or @Output are not being displayed. child.component.ts @Component({ selector: 'app-form-input', templateUrl: './form-input.component.ht ...

``Using backticks to denote HTML syntax - Leveraging Google Charts to create

Has anyone found a way to incorporate HTML in ticks within a Google chart? I am attempting to insert a weather icon from This is my current attempt: const dailyData = new google.visualization.DataTable(); dailyData.addColumn('timeofday' ...

Is it possible to utilize both $uibModal and $uibModalInstance within the same controller to create a modal popup in an Angular project incorporating TypeScript?

Being new to Angular with Typescript, I encountered an issue while trying to implement a modal popup in Angular. The problem arises when I have a dropdown menu that triggers the opening of a modal popup with two buttons, "Yes" and "No". To handle this, I h ...

Restrictions on classes in Typescript using generics

I'm currently working on a straightforward Local Storage utility method. My goal is to retrieve an entry based on a key and a specified type. Here's the implementation: get<T>(key: string): T { const data = localStorage.getItem(key); ...

What are the tips for using ts-node in the presence of errors?

While developing, I have encountered some issues with ts-node. When I need to test something, commenting out code is my usual approach. However, when using ts-node, I keep getting this error message: 'foo' is declared but its value is never rea ...

Tips for creating a Button component that can render either an <a> or <button> element and accept additional props

Currently in the process of creating a component that can return either an or a based on the specified prop "as". Additionally, I aim to spread the props from to whichever tag is rendered for enhanced flexibility. Challenge I am encountering difficulti ...

Tapping into the space outside the MUI Modal Component in a React application

Can Modal Component in MUI be used with a chat bot? When the modal is open, can users interact with buttons and inputs outside of it? How can this be implemented? I want to be able to click outside the modal without closing it. Modal open={open} onClo ...

Is it possible to devise a universal click handler in TypeScript that will consistently execute after all other click handlers?

In my ReactJS based application written in TypeScript, we have implemented various click handlers. Different teams contribute to the application and can add their own handlers as well. The challenge we face is ensuring that a specific global click handler ...

Ways to conceal a button according to a particular trigger

On the page labeled standing-orders-details, I have configured it so that the display of the New Order button is hidden, but only if I first visit the new-order page. To begin, I need to ensure that the New Order button remains hidden on the standing-or ...