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

Trigger a method within a component when there is a change in the Vuex state

I need to trigger a method inside a component whenever the vuex state changes in TypeScript and Vue.js. While I can access the vuex state value using getters in the template, I am unsure how to access the data within the component class. The vuex state is ...

In TypeScript, enhancing an interface with additional properties

Currently, I am working on an Angular project and have developed this interface to display some data: export interface UserData { name: string, vorname: string, strasse: string, plz: string, ort: string, handynummer: string, telefonnummer: s ...

Include html into typescript using webpack

Attempting to include HTML content into a variable using TypeScript and webpack has been my challenge. This is the current setup: package.json: { "devDependencies": { "awesome-typescript-loader": "^3.2.3", "html-loader": "^0.5.1", "ts-load ...

"Encountering a Prisma type error while attempting to add a new record

I am currently utilizing Prisma with a MySQL database. Whenever I attempt to create a new record (School), an error of type pops up in the console. Additionally, I am implementing a framework called Remix.run, although it does not seem to be causing the is ...

Converting a string[] to an EventEmitter string[] in Angular 4 with TypeScript: Step-by-step guide

Programming Language: Typescript – written as .ts files Development Framework: Angular 4 I'm currently working on an application that is supposed to add chips (similar to tags in Angular 1) whenever a user types something into the input box and hi ...

Typescript disregarding conditional statements

Looking for some assistance with a Next.JS React-Typescript application Here's my code snippet for handling the video HTML element const videoRef = useRef<HTMLVideoElement>(); useEffect(() => { videoRef !== undefined ? videoRef.current. ...

Leverage the power of react-redux useSelector with the precision of TypeScript

When attempting to utilize the new useSelector hook (shown in the example below) from react-redux in TypeScript, an error is encountered indicating that the function does not exist: Module '"../../../node_modules/@types/react-redux"' has no expo ...

Describing a function in Typescript that takes an array of functions as input, and outputs an array containing the return types of each function

Can the code snippet below be accurately typed? function determineElementTypes(...array: Array<(() => string) | (() => number) | (() => {prop: string}) | (() => number[])>) { /// .. do something /// .. and then return an array ...

Combine form data from a reactive form into a string using interpolation

Currently, I am working with an object that has a string property embedded within it. The string in this property contains interpolation elements. For my user interface, I have implemented a reactive form with an input field. My goal is to display the ent ...

Oops! There seems to be an issue with locating a differ that supports the object '[object Object]' of type 'object', like an Array

I'm currently encountering an error that reads: (ERROR Error: NG02200: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the key ...

Error occurs in Windows script while running a project installed globally

Upon installing my project globally, I encountered a Windows Script Host error. https://i.stack.imgur.com/unFVu.png What steps can I take to resolve this issue? The following is my JavaScript code snippet: Object.defineProperty(exports, "__esModule ...

When using TypeScript with Jest or Mocha, an issue arises where the testing frameworks are unable to read JavaScript dependencies properly, resulting in an error message saying "unexpected token

Currently, I am conducting testing on a TypeScript file using Mocha. Within the file, there is a dependency that I access via the import statement, and the function I need to test resides within the same file as shown below: import { Foo } from 'foo- ...

Guide to connecting data from the backend to the frontend in the select option feature using Angular 9

I have a backend system where I store a number representing a selected object, which I am trying to display in a select option using Angular. Currently, the select option only displays a list of items that I have predefined in my TypeScript code using enu ...

When calling UIComponent.getRouterFor, a TypeScript error is displayed indicating the unsafe return of a value typed as 'any'

I have recently integrated TypeScript into my SAPUI5 project and am encountering issues with the ESLint messages related to types. Consider this simple example: In this snippet of code, I am getting an error message saying "Unsafe return of an any typed ...

send the checkbox control's model value back to the parent control in Vue3

I've implemented a wrapper control for checkboxes that closely resembles my textbox control. This approach ensures consistent validation and design throughout the application. While I was successful in getting it to work for textboxes, I encountered s ...

Encountering a Typescript error while trying to implement a custom palette color with the Chip component in Material-UI

I have created a unique theme where I included my own custom colors in the palette. I was expecting the color prop to work with a custom color. I tested it with the Button component and it performed as expected. However, when I attempted the same with the ...

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 ...

Issue with Object.keys printing in an abnormal manner

My goal is to extract only the keys from an object, but instead of getting the desired output with the keys, I am seeing numbers. Here is the code snippet: data = {"property" : "{\"animalID\": \"12345\" ...

Constructor polymorphism in TypeScript allows for the creation of multiple constructor signatures

Consider this straightforward hierarchy of classes : class Vehicle {} class Car extends Vehicle { wheels: Number constructor(wheels: Number) { super() this.wheels = wheels } } I am looking to store a constructor type that ext ...

Is it possible for a class that implements an interface to have additional fields not defined in the parent interface?

Looking at the code snippet below, my aim is to ensure that all classes which implement InterfaceParent must have a method called add that takes an instance of either InterfaceParent or its implementing class as input and returns an instance of InterfacePa ...