TypeScript error message: "The 'new' keyword cannot be used with an expression that does not have a call or construct signature."

Encountered a problem with intersection types in TypeScript...

There are three type aliases:

  • Prototype<T> - representing an object or class with a prototype property.
  • DefaultCtor<T> - representing an object or class with a default constructor.
  • ParameterizedCtor<T> - representing an object or class with a parameterized constructor.

Experimented with the following intersection combinations:

  • Prototype<T> & DefaultCtor<T>
    - functioning correctly.
  • Prototype<T> & ParameterizedCtor<T>
    - encountering a compiler error.

Example

type Prototype<T> = {
    prototype: T;
}

type DefaultCtor<T> = {
    new(): T;
}

type ParameterizedCtor<T> = {
    new(...args: any[]): T
}

function makeDefault<T>(ctor: Prototype<T> & DefaultCtor<T>): T {
    return new ctor();
}

function makeWithArgs<T>(ctor: Prototype<T> & ParameterizedCtor<T>, ...args: any[]): T {
    return new ctor(...args);
    // ERROR: Cannot use 'new' with an expression whose type lacks a call or construct signature.
}

Test it out in the Playground

Error The issue arises with the

Prototype<T> & ParameterizedCtor<T>
intersection:

Cannot use 'new' with an expression whose type lacks a call or construct signature.

Questioning why the TypeScript compiler can determine the presence of a constructor in the

Prototype<T> & DefaultCtor<T>
intersection type, but not in the
Prototype<T> & ParameterizedCtor<T>
intersection type?

Answer №1

It appears that there is a well-known issue reported on Microsoft/TypeScript#17388, back in July of 2017. The fix was originally planned for TypeScript v2.9, but it seems to have been delayed multiple times. Feel free to visit the link and give it a thumbs up if you agree with the sentiment. Wishing you the best of luck.

Answer №2

Workaround

If you find yourself in a tricky situation, using a cast can act as a temporary solution until the TypeScript team releases a permanent fix.

Illustration

function create<T>(constructor: Prototype<T> & ParameterizedCtor<T>, ...arguments: any[]): T {
    console.log(constructor.prototype);
    return new (constructor as ParameterizedCtor<T>)(...arguments);
}

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

SolidJS directives utilizing use:___ result in TypeScript errors when used in JSX

As I work on converting the forms example from JS to TS, I came across a typescript error related to directives in HTML: https://i.sstatic.net/Hl8Pv.png It appears that validate and formSubmit are being recognized as unused variables by typescript, result ...

Guide on categorizing MUI icon types

My current code snippet is as follows: type MenuItem = { key: string; order: number; text: string; icon: typeof SvgIcon; }; However, when I attempt to use it in my JSX like this: <List> {MENU.map((menuItem: MenuItem) => ( ...

Angular-template static functions refer to functions that do not require an

Our project utilizes the linting-config provided by AirBnB. There is a rule that stipulates class methods must utilize this or be declared as static. While this rule theoretically makes sense, it seems to present challenges within an angular context. Consi ...

Adjust the appearance of matSelect when the selection menu is activated

What is the best way to adjust mat-select properties when its options are open? <mat-select class="selector"> <mat-option><mat-option> </mat-select> .selector:focus { color: green; } I attempted using focus, but ...

Switching between PascalCase and camelCase in TypeScript leads to unexpected behavior

Currently, I am in the process of transitioning a C# desktop application to an Angular/TypeScript web application. In the C# application, all class properties are named using PascalCase. Therefore, I decided to maintain this naming convention in the TypeS ...

Encountering difficulty importing a module from a different module within Nuxt

Within my Nuxt project directory, there exists a specific folder named modules which houses my customized modules. For this illustration, it includes the modules foo and bar. The inclusion of foo in the nuxt.config.js file appears as follows: // nuxt.confi ...

Incorporate dynamic HTML snippets into the DOM with Angular 4

Looking to populate an unordered list element <ul> with small, straightforward snippets from my JavaScript. Just basic lines like <li>Label: Text</li>. Using the ViewContainerRef.createComponent(ItemComponent) method to create a new comp ...

Improving DynamoDb Query Results with Type Hinting

In the following Typescript code, how can I specify which fields should be present in my Query Items Result? const request: DynamoDB.DocumentClient.QueryInput = { TableName: UnsubscriptionTokensRepository.TABLE_NAME, IndexName: 'TokenIndex&ap ...

What is the proper way to create an array of dynamically nested objects in TypeScript?

Consider the structure of an array : [ branch_a: { holidays: [] }, branch_b: { holidays: [] }, ] In this structure, branch_a, branch_b, and ... represent dynamic keys. How can this be properly declared in typescript? Here is an attempt: ty ...

What could be causing the rapid breakage of the socket in Ionic 3's Bluetooth Serial after just a short period

Although the code appears to be functioning correctly, it loses connection shortly after establishing it. This snippet contains the relevant code: import { Component } from '@angular/core'; import { Platform, NavController, ToastController, Ref ...

Utilize a variable within a regular expression

Can the variable label be used inside a regex like this? const label = 'test' If I have the regex: { name: /test/i } Is it possible to use the variable label inside the regex, in the following way? { name: `/${label}/i` } What do you think? ...

An error occurred: Unable to access the 'basemapLayer' property due to it being undefined

Oops! TypeError: Unable to access 'basemapLayer' property of undefined I recently put together a simple application using the Angular CLI. After successfully building and running the application with ng serve -o, I encountered an issue in Chrome ...

Is it possible to eliminate a parameter when the generic type 'T' is equal to 'void'?

In the code snippet below, I am attempting to specify the type of the resolve callback. Initially: Generic Approach export interface PromiseHandler<T> { resolve: (result: T) => void // <----- My query is about this line reject: (error: a ...

Having trouble connecting Nextjs with ChromaDB?

I am encountering issues while trying to establish a connection with the Chromadb vector database in Nextjs. The objective is to store user-generated content in Chromadb. Below is the code snippet I am utilizing along with its dependencies: Dependencies V ...

Vue: Storing selected list values in an array

I am working on a Vue application where I need to select two elements from a list component and place them inside an array. Currently, I have my list set up with selection functionality thanks to Vuetify. I have bound the selected items to an array using v ...

Merge the values of an object's key with commas

I'm dealing with an array of objects that looks like this: let modifiers = [ {name: "House Fries", price: "2.00"}, {name: "Baked Potato", price: "2.50"}, {name: "Grits", price: "1.50"}, {name: "Nothing on Side", price: "0.00"} ] My goal is to con ...

What are the steps to correct a missing property in an established type?

Currently, I am in the process of converting an existing Node.js + express application from plain JS to TypeScript. Although I understand why I am encountering this error, I am unsure about the correct approach to resolve it. The type "Request" is coming f ...

Encountering issues with upgrading Vue.js 2.5.2 with TypeScript

I am currently in the process of updating vue js to version 2.5.2 along with typescript 2.5.3. Below is my index.ts file: import Vue from 'vue' var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' ...

The OnPrepareResponse method in StaticFileOptions does not trigger when serving the index.html file

Currently, I am attempting to disable caching for index.html in my Angular SPA that is connected to a .NET Core 2.2 backend. I am following the instructions provided in this particular answer by implementing an OnPrepareResponse action for my StaticFileOp ...

How can a Firestore Timestamp object be correctly created within a rules test data set?

I am in the process of writing tests for Firestore rules, focusing on testing rules that control when actions can be executed based on a timestamp stored in the document. It is important to note that the rules will utilize rules.Timestamp rather than Java ...