Can TypeScript use `extends` or `implements` to enforce constructor parameter types?

After conducting thorough research, I have reviewed the following resources:

  1. Abstract constructor type in TypeScript

  2. How does `type Constructor<T> = Function & { prototype: T }` apply to Abstract constructor types in TypeScript?

  3. Abstract Constructor on Abstract Class in TypeScript

Out of these, the third resource seemed closest to addressing my query, but unfortunately, the answer focused more on a specific issue rather than the overarching question.

To provide some context, here is an example of what I aim to achieve:

abstract class HasStringAsOnlyConstructorArg {
  abstract constructor(str: string);
}

class NamedCat extends HasStringAsOnlyConstructorArg {
  constructor(name: string) { console.log(`meow I'm ${name}`); }
}

class Shouter extends HasStringAsOnlyConstructorArg {
  constructor(phrase: string) { console.log(`${phrase}!!!!!!`); }
}

const creatableClasses: Array<typeof HasStringAsOnlyConstructorArg> = [NamedCat, Shouter];
creatableClasses.forEach(
  (class: typeof HasStringAsOnlyConstructorArg) => new class("Sprinkles")
);

In this demonstration, both Shouter and NamedCat require only one string argument for their constructors. While they could potentially implement an interface instead of extending a class, my goal is to compile a list of classes that necessitate identical arguments for instantiation.

My primary inquiry pertains to whether it is feasible to enforce a class's constructor parameter types using extends or implements in TypeScript.

EDIT: The "Possible Duplicate" reference indicates the limitations of utilizing new() within an interface for this purpose. Consequently, I am exploring alternative methodologies to address this challenge.

Answer №1

To ensure that only constructors with a single string argument are allowed, you can implement the enforcement directly on the array itself:

class NamedCat {
    constructor(name: string) { console.log(`meow I'm ${name}`); }
}

class Shouter {
    constructor(phrase: string) { console.log(`${phrase}!!!!!!`); }
}

type ConstructorWithSingleStringArg = new (args: string) => any;

const creatableClasses: Array<ConstructorWithSingleStringArg> = [NamedCat, Shouter];
creatableClasses.forEach(
    ctor => new ctor("Sprinkles")
);

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

Tips for simulating localStorage in TypeScript unit testing

Is there a method to simulate localStorage using Jest? Despite trying various solutions from this post, none have proven effective in TypeScript as I continue encountering: "ReferenceError: localStorage is not defined" I attempted creating my ...

Attempting to compile TypeScript by referencing ng2-bootstrap using Gulp within Visual Studio

I've been struggling with this issue for a few days now, and I'm really hoping someone can help me out. Currently, I am experimenting with Angular2 in an aspnet core project. The setup involves using a gulpfile.js to build .ts files and transfer ...

Updating the function type definition in TypeScript after importing it into a separate file

I have created a unique hook named useDropdownSelection. It's a straightforward one. Take a look at the code below: import { useState } from 'react' export const useDropdownSelection = (initialValue: string) => { const [selectedOption, ...

Steps for resolving the problem of the Express error handler not being executed

This question has come up again, and I have searched for solutions but none seem to work. Your assistance in debugging the issue would be greatly appreciated. I have a separate errorHandler set up as middleware. In my error-handler.ts file: import expres ...

Typescript compilation fails to include require statements in certain files

Currently, I am in the process of converting a Node.js project to TypeScript. The first two main files of the Node project transpiled correctly, but the third file ran into issues with the requires statement at the top for pulling in dependencies. Despite ...

What is the process for updating Typescript to the most recent version?

My MacBook Pro is running OS X 10.8.2 and I previously installed Typescript. Now, I want to update it to the latest version (v0.8.3). I used this command in the terminal: sudo npm install -g typescript However, the output displayed was: npm http GET ht ...

Tips for preventing circular dependencies when using combineSlices in Redux-toolkit

When utilizing combineSlices with createAsyncThunk condition, I find it challenging to avoid circular dependency. My store initiation thunk looks like this: thunk.ts export const initiateFx = createAsyncThunk< InitiatePayload, string, { state: R ...

Transform JSON reply in JavaScript/Typescript/Angular

Looking for assistance with restructuring JSON data received from a server API for easier processing. You can find the input JSON file at assets/input-json.json within the stackblitz project: https://stackblitz.com/edit/angular-ivy-87qser?file=src/assets/ ...

Discover similarities between two arrays

My goal is to compare two arrays and generate a JSON array marking true if there's a match and false if there isn't. The second array will always have values that match some from the first, and it will be smaller as it's derived from the fir ...

I'm trying to figure out the best way to successfully pass a prop to another component in TypeScript without running into the frustrating issue of not being able to

I have been facing an issue while trying to pass a prop from a custom object I have defined. The structure of the object is as follows: export type CustomObjectType = { data?: DataObject }; export type DataObject = { id: number; name: stri ...

Tips for writing an async function using TypeScript

I've been working with Typescript and NLP.js. However, I'm encountering an issue where the argument manager is displaying 'Parameter manager implicitly has an any type'. I attempted to use :, but it didn't solve the problem eff ...

The console is displaying 'undefined' when attempting to render the JSON response in Vue

In my vue.js application, I'm trying to display text using TypeScript. Here is an example of the JSON response: { "data": [ { "firstName": "Foo", "lastName": "Smith" }, { "firstName": "Mi ...

ExplorifyStack, WebDriveIO, CukeIt, TypewiseScript

I'm currently working on setting up my automation tests using Cucumber, TypeScript, WebdriverIO, and BrowserStack. It seems like there is no recent setup guide available for this particular stack, and I've run into some issues with TypeScript. D ...

Is there a method to improve type inference in vscode?

Recently, I created a component with a click handler that looks like this: onClick={(e) => { e.stopPropagation(); }} It seems clear to me, but then the Typescript compiler complains that it's not a valid signature for onClick, which actually a ...

There was an error in parsing the module: an unexpected token was encountered during the rendering

Recently, I've been working on configuring React with Typescript (for type checking), Babel for code transpilation, Jest for testing, ESLint for code checking, and a few other tools. You can find all the necessary files in the repository linked below. ...

Menu with options labeled using IDs in FluentUI/react-northstar

I'm currently working on creating a dropdown menu using the FluentUI/react-northstar Dropdown component. The issue I'm facing is that the 'items' prop for this component only accepts a 'string[]' for the names to be displayed ...

Converting API data to an array map in React with Typescript

There is an array data retrieved from an API that needs to be rendered in a React TypeScript file using the map function. { "data":{ "cart":{ "1":{ "product_id":1, "name":"Product 1", "quantity":1, ...

Using TypeScript to pass the text field ID to a function for clearing the text field with a button

I am looking for a way to improve the functionality of my web page featuring several buttons that will clear different text boxes on the same line. Currently, I am using separate functions for each button, but my goal is to streamline this process by utili ...

When attempting to register a custom Gamepad class using GamepadEvent, the conversion of the value to 'Gamepad' has failed

I have been working on developing a virtual controller in the form of a Gamepad class and registering it. Currently, my implementation is essentially a duplicate of the existing Gamepad class: class CustomController { readonly axes: ReadonlyArray<nu ...

What advantages does using an RxJS Subject have over handling multiple event listeners individually in terms of speed

After investigating a page's slow performance, I identified an angular directive as the root cause. The culprit was a piece of code that registered event listeners on the window keydown event multiple times: @HostListener('window:keydown', ...