Tips for creating a list of objects that inherit from a base object and have generic types

What is the proper way to define a list of objects that extend another class using generics?

I am looking for a solution where I can declare something like "anything that extends A", without specifying a specific generic type for each object.

// valid abstract class
abstract class A<SOME_TYPE> {
  private something: SOME_TYPE;
  constructor(xxx: SOME_TYPE) {
    console.log(xxx);
  }
}

// valid class
class B extends A<number> {}


// How do I create a list of objects that extend A?
const listOfObjects: Record<string, A<any>> = {
  b: B, // TS2741 error
};
// Attempted solutions that didn't work:
const listOfObjects: Record<string, typeof A> = {
  b: B, // Type 'typeof B' is not assignable to type 'typeof A'
};

Using TypeScript version 4.4.4

Answer №1

Utilizing construct signatures is recommended for defining types.

abstract class A<SOME_TYPE> {
  private something!: SOME_TYPE;

  constructor(arg: string) {}
}

class B extends A<number> {}
class C extends A<number> {}

const listOfObjects: Record<string, new (...args: any) => A<any>> = {
  b: B,
  c: C
};

Interactive Code Playground

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

Messages are not being emitted from the socket

I've been encountering an issue with message transmission from client to server while using React and ExpressJS. When I trigger the sendMessage function on the client side, my intention is to send a message to the server. However, for some reason, the ...

Angular2/Typescript: Transforming a Javascript/Typescript Date into a C# DateTime string on the client side

Currently immersed in an Angular2/Typescript project, I am faced with the task of sending a date to a C# backend. Despite my extensive research, all I could uncover through Google searches was information on converting the date on the backend side. My la ...

Children components are not re-rendered by React

I created a basic task manager, but I'm encountering issues when trying to manage all the data from a single point within the TaskManager component. Essentially, I have a TaskManager component that acts as the container for all the data. Within this ...

Create and save data to a local file using Angular service

I am facing an issue with my Angular service: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { person } from '../interfaces/iperson ...

Struggling with a Nextjs Stripe issue? The expected signature for payload does not match any found signatures

Struggling to integrate data from Stripe check out events into my orders database, facing issues with finding the signature while testing the web hook. Check out route: app/api/webhooks/checkout/route.ts import Cors from "micro-cors"; import { h ...

An array in Typescript containing elements of type MyType<T> with T being different for each element

TL;DR Is there a way to create an array of tuples where the second element is automatically derived from the first? Check out the example playground to see the code below in action. My scenario I'm using a tool called Puppeteer to navigate through ...

The term "Exports" has not been defined

I'm currently facing a challenge trying to develop an Angular application based on my initial app. The process is not as smooth as I had hoped. Here's the current setup: index.html <!DOCTYPE html> <html> <head> <base h ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

What would be the most stylish approach to restructure this code, especially when the only variation is the name of the key in the returned object?

Is there a more elegant solution for restructuring this code, especially considering the only variation is in the key name of a return object? function generateContactInput(rawData, contactId) { const data = rawData ? rawData.replace(/["]+/g, &a ...

I am looking to transfer information from Angular 4 to Java servlet (cross-domain)

Having trouble sending data from Angular 4 to a Java servlet due to access control restrictions. Need to figure out how to properly insert data into the database using the Java servlet. Here is my code snippet: import { Injectable } from '@angular/ ...

Issue with font-size changes using css variables in Angular not updating in browser for specific fields

Utilizing CSS variables, I have implemented a feature that allows users to adjust the font size to small, medium, or large. While this functionality works correctly for most fields, there are certain instances where the value is applied but not displayed. ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

Angular2: Promise Rejection: Quotes cannot be used for evaluation in this component

I'm currently working on a component in Angular that includes an input parameter: import {Component, Input} from '@angular/core'; @Component({ selector: 'comment', template: ` <div class="col-lg-6 col-md-6 ...

Monitoring URL changes in Angular2 using the HostListener

I have a common navbar component that is included in every page of my website. I would like it to detect when the URL changes using a HostListener. @HostListener('window:hashchange', ['$event']) onHashChange(event) { this.checkCu ...

Utilize Ngrx to keep an eye on specific items within the store

If we consider an interface called INotification: export interface INotification { id: number; DateReceived: number; Title: string; Message: string; Tipology: string; isRead: number; } and a reducer system. In the component, it&ap ...

Typescript iteration: Exploring an iterable through multiple traversals

What is a practical approach to handling multiple traversals over an Iterable in Typescript? Typically, an Iterable can only be traversed once before it exhausts all its elements. For instance, an IterableIterator behaves this way. To traverse a sequence ...

Retrieve all items that match the ids in the array from the database

I'm having trouble receiving a list of items that match with my array of ids. Here's a snippet from the Angular component code: this.orderService.getSpecyficOrders(ids) .subscribe(orders => { ... Where ids is an array of [{_id : ID }, ...

Inject SCSS variables into Typescript in Vue 2 Using Vue-cli 5

When working on my Vue 2 project (created using the Vue-cli v4), I successfully imported variables from my SCSS file into my typescript (.vue files) without any issues. I had the :export { ... } in my SCSS file _variables.scss, along with shims.scss.d.ts ...

Returning a value with an `any` type without proper validation.eslint@typescript-eslint/no-unsafe-return

I am currently working on a project using Vue and TypeScript, and I am encountering an issue with returning a function while attempting to validate my form. Below are the errors I am facing: Element implicitly has an 'any' type because expression ...

NestJS encounters an issue with the SQS Listener Module, specifically a TypeError when attempting to read properties that are undefined, such as 'meta'

I've been working on integrating the SQS service into my Nest.js project using the @ssut/nestjs-sqs library. However, I've hit a roadblock with an error message that says "No metadata found for: undefined" pointing to the sqs.service.js file in t ...