Providing the type for an abstract class implementation: A guide

Is there a way to define a type for "any class that implements this abstract class"?

For instance:

// LIBRARY CODE
abstract class Table {
  static readonly tableName: string;
}
type TableConstructor = typeof Table;
// type TableConstructor = (new (...args: never) => Table);
const createORM = (tables: Array<TableConstructor>) => {
  return {
      executeQuery() {
        // What should be the type of the "tables" array 
        // to accommodate both of the following two lines
        console.log(tables[0].tableName)
        return new tables[0]();
        //     ~~~~~~~~~~~~~~~~
        // Cannot instantiate an abstract class
      }
  }
}


// EXAMPLE USER CODE
class Foo implements Table {
  static get tableName() {
      return 'foo';
  }
}
const orm = createORM([Foo]);

TypeScript Playground Example Link

Answer №1

interface TableConstructor {
  new (...args: never): Table;
  readonly tableName: string;
}

or you can also use

type TableConstructor = (new (...args: never) => Table) & Omit<typeof Table, never>;

Here is the example with this implementation

Answer provided on the TypeScript discord:

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

Entering key-value pairs into a dictionary to show correlation

I've been struggling to find a solution for what seems like a simple issue. The problem lies in typing a dictionary with values of different types so that TypeScript can infer the type based on the key. Here is the scenario: type Id = string; inter ...

MUI version 5 with styled-components and ListItemButton: The specified property 'to'/'component' is not recognized

While transitioning from MUI v4 to v5, I encountered a hurdle: in v4, I utilized makeStyles(), but now aim to fully switch to styled(). Unfortunately, I am struggling to get Typescript to recognize a styled(ListItemButton)(...) with to= and component= attr ...

Store a video file on your device's memory

Currently, I am storing simple strings in local storage. However, I am now facing the issue of wanting to save videos and images to local storage. Due to the limitations of localStorage supporting only strings, I am unsure of how to achieve this. If you h ...

Exploring the capabilities of renderOption within Material-UI's AutoComplete functionality

Hey there, I've been pondering a question lately and could really use some help. I've been trying to set up my autocomplete feature to display a label in the options while having a different value. After doing some research, I learned about usin ...

Encountered an error stating "Cannot find module node:fs" while using eslint-typescript-import, eslint-import-resolver-typescript,

Challenge My attempt to configure path alias in my TypeScript project was met with failure. Two errors arose during the execution of npm start: Module not found: Error: Can't resolve '~/App' in 'D:\work\workbench\templa ...

Even as I create fresh references, my JavaScript array object continues to overwrite previous objects

Coming from a background in c# and c++, I am facing some confusion with a particular situation. Within the scope of my function, I am creating a new object before pushing it into an 'array'. Strangely, when I create the new object, it appears to ...

How to identify generic return type in TypeScript

My goal is to develop a core dialog class that can automatically resolve dialog types and return values based on the input provided. I have made progress in implementing this functionality, but I am facing challenges with handling the return values. Each ...

Obtain unfinished designs from resolver using GraphQL Code Generator

In order to allow resolvers to return partial data and have other resolvers complete the missing fields, I follow this convention: type UserExtra { name: String! } type User { id: ID! email: String! extra: UserExtra! } type Query { user(id: ID! ...

Using TypeScript with React's forwardRef

Here's my code where I have utilized React's forwardRef: interface PropsDummy {} const ProfileMenu = forwardRef<HTMLInputElement, PropsDummy>((props, ref) => { console.log(ref.current); } However, I'm encountering a TypeScript e ...

When using this.$refs in Vue, be mindful that the object may be undefined

After switching to TypeScript, I encountered errors in some of my code related to: Object is possibly 'undefined' The version of TypeScript being used is 3.2.1 Below is the problematic code snippet: this.$refs[`stud-copy-${index}`][0].innerHTM ...

In Next.js, I am experiencing an issue where the Tailwind class is being added, but the corresponding

I'm currently in the process of developing a board game where I need to track players and their positions on specific squares. My goal is to display a small colored dot on the square where each player is positioned. Here's a snippet of my templa ...

The 'roleName' property is not found within the 'never' data type

// ** React Component and Library Imports import { useEffect, useState } from 'react' import Box, { BoxProps } from '@mui/material/Box' import Button from '@mui/material/Button' import Drawer from '@mui/material/Drawer&ap ...

The Angular route successfully navigated to the page, but the HTML content was not

Whenever I select the Home option in the navigation bar, it takes me to the home URL but doesn't display the HTML content. Below is my app.routing.module.ts code: import { Component, NgModule } from '@angular/core'; import { RouterModule, Ro ...

Unable to place value into an array following the invocation of a function in Angular 9

Within an array I established, I am encountering an undefined value when I use console.log. Take a look at my component.ts below: export class OrderExceptionReportComponent implements OnInit { public sessionData: ExceptionReportSessionData[] = []; n ...

Unable to retrieve the request body with bodyParser

I am currently working on a NextJS React Application. Within my server/index.tsx file, I have the following code: import next from 'next'; import express from 'express'; import compression from 'compression'; import bodyParser ...

Is there a way for me to retrieve the value that has been set within the cy.get() function in Cypress using Typescript?

Is there a way to retrieve the value of the getLength function without it returning undefined? How can I access the value in this case? Here is my code snippet: const verifyValue = () => { const selector = 'nz-option-container nz-option-item&apo ...

Guide on sending files and data simultaneously from Angular to .NET Core

I'm currently working on an Angular 9 application and I am trying to incorporate a file upload feature. The user needs to input title, description, and upload only one file in .zip format. Upon clicking Submit, I intend to send the form data along wit ...

JavaScript method of retrieving an object inside an array nested within another object via multer

Below is my custom multer function to handle file uploads - const storage = multer.diskStorage({ destination: (req, file, callback) => { let type = req.params.type; let path = `./data/${type}`; fs.mkdirsSync(path); callback(null, path) ...

Is there a way to change a typescript enum value into a string format?

I'm working with enums in TypeScript and I need to convert the enum value to a string for passing it to an API endpoint. Can someone please guide me on how to achieve this? Thanks. enum RecordStatus { CancelledClosed = 102830004, Completed = ...

Unlocking the accordion feature in Ionic 3 form: A step-by-step guide

I am currently working on a search form and want to incorporate it within an accordion so that users can simply click to expand the form. Below is the code snippet: TS. buildForm(): void { this.form = this.fb.group({ username: new FormControl(& ...