The type 'Function' does not contain any construct signatures.ts

Struggling to transition my JS code to TS, specifically with a class called Point2D for handling 2 dimensional points. Encountering an error message stating

Type 'Function' has no construct signatures.ts(2351)
. Any insights on what might be going wrong in the TypeScript conversion?

class Point2D {
    x: number;
    y: number;
    public constructor(x: number = 0, y: number = 0) {
      this.x = x;
      this.y = y;
    }
  
    /**
     * Translate this point by that point
     *
     * @param {Point2D} that
     */
    public add(that: Point2D) {
      return new this.constructor(this.x + that.x, this.y + that.y); // ERROR
    }
  
    public subtract(that: Point2D) {
      return new this.constructor(this.x - that.x, this.y - that.y); // ERROR
    }
  
    /**
     *
     * @param {number} scalar
     */
    public multiply(scalar:number) {
      return new this.constructor(this.x * scalar, this.y * scalar); // ERROR
    }
  }
  
  export default Point2D;
  

Answer №1

The issue in your code stems from inheriting a base class with a subclass that does not have the same constructor argument list as the base class. Therefore, calling `new this.constructor(...args)` is risky for any arguments passed. For instance:

class StringPoint extends Point2D {
    constructor(x: string, y: string) {
        super(x.trim().length, y.trim().length);
    }
}

const s = new StringPoint("abc", "defgh  ");
console.log(s.x) // 3
console.log(s.y) // 5

In the example above, the `StringPoint` class extends `Point2D`, but its constructor takes two strings instead of numbers. This code works fine until you invoke a method from the base class that calls `new this.constructor`, resulting in a runtime error:

console.log(s.multiply(2)) // 💥 ERROR! x.trim is not a function

This error occurs because `s.multiply(2)` ends up executing `new this.constructor(6, 10)` where `this` refers to an instance of `StringPoint`, causing `this.constructor` to be `StringPoint`. As a result, `new StringPoint(6, 10)` is called, passing numbers when strings are expected, leading to a `trim()` method error.


To rectify this issue, it is advisable to use the `Point2D` constructor directly instead of relying on the instance's constructor:

public add(that: Point2D) {
    return new Point2D(this.x + that.x, this.y + that.y); // okay
}

public subtract(that: Point2D) {
    return new Point2D(this.x - that.x, this.y - that.y); // okay
}

public multiply(scalar: number) {
    return new Point2D(this.x * scalar, this.y * scalar); // okay
}

This approach works since `Point2D` specifically expects two numbers as arguments. The previous `StringPoint` example now functions correctly without issues because the base class methods always create instances of the base class and do not attempt to construct incompatible subclasses:

const s = new StringPoint("abc", "defgh  ");
console.log(s.x) // 3
console.log(s.y) // 5
console.log(s.multiply(2)) // okay, {x: 6, y: 10}

Here, `s.multiply(2)` returns a `Point2D` object rather than a `StringPoint` object.


It's essential to note that TypeScript's typings for the `constructor` property can sometimes be misleading; `this.constructor` is considered to be of type `Function` or an "untyped call." This situation is both too strict and too loose, potentially leading to errors at runtime.

When handling the `constructor` property in TypeScript, caution should be exercised to avoid unexpected behavior and errors.

Link to 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

Initializing variables in Angular2 templates

I am facing an issue where, upon running the application, the console displays all the logs from the ngOnInit function, but the actual view only shows a skeleton without the component variables and text from l18n. It seems like the ngOnInit is not working ...

What could be causing the conditional div to malfunction in Angular?

There are three conditional div elements on a page, each meant to be displayed based on specific conditions. <div *ngIf="isAvailable=='true'"> <form> <div class="form-group"> <label for ...

Issue with BehaviorSubject<Object[]> causing incorrect array data upon initial subscription

I am facing an issue with a BehaviorSubject where the first .subscribe callback is returning an Array with 6 Objects. Strangely, in console output, it shows length: 6, but every for-loop I iterate through the array only runs 5 times and even when I log arr ...

Exploring Methods to Define Class Types as Parameter Types in Typescript

Is there a way to pass type information for a class, indicating to the compiler that the provided parameter is not an instance of a class but rather the definition of the class itself? import * as Routes from '../routes'; import * as Entities fr ...

Having trouble installing memlab using the npm package

Recently, I made an attempt to install the memlab library from Meta's GitHub. Initially, when I installed it without using the -g flag, the installation was successful. However, I encountered an issue where I could not execute any of the memlab comman ...

TypeScript fails to acknowledge an exported enum

Currently utilizing TypeScript version 2.5.3 along with Angular 5. I have an enum defined in a separate file as follows: export enum eUserType { Driver = 1, Passenger = 2, User = 3 } To import and use it in another ts file, I do the following: i ...

The best approach to typing a FunctionComponent in React with typescript

I'm diving into the world of React and TypeScript for the first time. Could someone verify if this is the correct way to type a FunctionComponent? type ModalProps = { children: ReactElement<any>; show: boolean; modalClosed(): void; }; co ...

Display a modal dialog using HttpInterceptor

@Injectable() export class MyInterceptor implements HttpInterceptor { intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> { //display a modal dialog to wait for user response before proceeding with t ...

Utilizing a created OpenAPI client within a React application

Using the command openapi-generator-cli generate -i https://linktomybackendswagger/swagger.json -g typescript-axios -o src/components/api --additional-properties=supportsES6=true, I have successfully generated my API client. However, despite having all th ...

Automatic type inference for functions in TypeScript with arguments

I am looking to define an interface with the following structure: interface CheckNActSetup<D, C> { defs: (event: Event) => D, context: (defs: D) => C; exec: (context: C) => any[]; when: ((context: C) => boolean)[]; } and implement it usi ...

[ERROR] There was a problem encountered during the execution of the ionic-app-scripts subprocess

I encountered an error while running my Ionic project. Below is the error message: [ERROR] ionic-app-scripts has unexpectedly closed (exit code 1). The Ionic CLI will exit. Please check any output above for error details. ionic3-firebase-shopping-car ...

Creating an interface or type in Typescript with a nested object property that uses keys from the same interface

I am looking to create an interface or type that can restrict the nested object properties based on keys defined in the main interface. class MyClass implements MyInterface { prop1: string; promp2: number; nestedObj: { prop1: string; // Allowed a ...

Is there a way to prevent an item from being selected in a Select component when the first letter of the option is pressed?

I'm currently working with the material UI Select component and I'm attempting to create a filter within it that will only display items matching the user's input. Below is a simplified example of my current project: function App() { con ...

If every single item in an array satisfies a specific condition

I am working with a structure that looks like this: { documentGroup: { Id: 000 Children: [ { Id: 000 Status: 1 }, { Id: 000 Status: 2 ...

Tips for sending icons as properties in React using TypeScript

Recently diving into typescript, I embarked on a straightforward project. Within this project lies a sidebar component that comprises multiple sidebarNavigationItem components. Each of these Sidebar items consists of an Icon and Title, showcased below. Si ...

Recursive rendering of tree components in React

I am facing a challenge in rendering tree items recursively using React. I have been struggling to achieve the desired outcome as calling treeRender(children) seems to alter the data structure when a folder is encountered for the first time. I am curious a ...

Using TypeORM: Implementing a @JoinTable with three columns

Seeking assistance with TypeORM and the @JoinTable and @RelationId Decorators. Any help answering my question, providing a hint, or ideally solving my issue would be greatly appreciated. I am utilizing NestJS with TypeORM to create a private API for shari ...

Error: Axios header not refreshing automatically in React. User must manually refresh the page

After logging in, I want to update the JWT token in the header before redirecting to the home page. Login.tsx ... const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); const data = new FormData(event.curr ...

Time taken for a webpage to finish loading

Is there a way to programmatically obtain the page load time in an Angular application? Situation: On my dashboard page, various components are making multiple calls. I want to calculate the overall time it takes to load all widgets on the page. ...

Tips on configuring a segment in an Angular 6 route

Question: I am looking to configure a specific segment after the user logs in, for example http://localhost:4200/#/{dynamic name}/{dynamic name}/app/... However, I am facing an issue when navigating to /app/... across the application. Is there a way to a ...