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

Is it possible to create my TypeORM entities in TypeScript even though my application is written in JavaScript?

While I find it easier to write typeorm entities in TypeScript format, my entire application is written in JavaScript. Even though both languages compile the same way, I'm wondering if this mixed approach could potentially lead to any issues. Thank yo ...

Is there a way to update components in Angular without affecting the current URL?

I want to update a component without changing the URL. For example, I have a component called register. When I visit my website at www.myweb.com, I would like to register by clicking on sign up. How can I display the register component without altering the ...

Troubleshooting issue with applying hover effect to child divs

How come when I hover over one of the child items in my parentDiv, the background of the last childDiv changes no matter which child I place my mouse on? for (let i = 0; i < Number(height); i++) { for (let j = 0; j < Number(width); j++ ...

Creating a custom definition file for TypeScript

Currently, I am facing an issue with a third-party library that provides global functions similar to jQuery ($ .functionName()), but unfortunately there is no definition file available. Due to this, my attempt to write my own file has been unsuccessful as ...

Filter multiple columns in an Angular custom table with a unique filterPredicate

Looking to develop a versatile table that accepts tableColumns and dataSource as @Input(). I want the ability to add custom filtering for each table column. Currently, I've set up the initialization of the table FormGroup and retrieving its value for ...

Angular Error TS2554: Received x arguments instead of the expected 0 on piped operators

I encountered an issue with Error TS2554: Expected 0 arguments, but got 4 when dealing with the observable getHappyDays(). The getHappyDays() Observable returns either Observable<HttpResponse<IHappyDays>> or Observable<HttpErrorResponse> ...

Problem with Angular Slider

I'm in the process of creating a carousel component in Angular, but I'm facing an issue where the carousel is not appearing as it should. Below is the code for my carousel component. carousel.component.html: <div class="carousel"> ...

Every instance of 'WeakMap' must include the same type parameters

While developing an Ionic App, I encountered a strange issue. Everything was running smoothly until I cloned the source code to a different machine, which resulted in an error that is displayed in the attached image. Even though there are no compilation e ...

The BooleanField component in V4 no longer supports the use of Mui Icons

In my React-Admin v3 project, I had a functional component that looked like this: import ClearIcon from '@mui/icons-material/Clear' import DoneIcon from '@mui/icons-material/Done' import get from 'lodash/get' import { BooleanF ...

Add integer to an array of strings

Currently, I am utilizing an autocomplete feature and aiming to save the IDs of the selected users. My goal is to store these IDs in a string array, ensuring that all values are unique with no duplicates. I have attempted to push and convert the values u ...

Enhancing the type safety of TypeScript Generics

Uncertainty looms over me - am I committing an error, or is this all part of the plan... Within my academic domain class Collection<E> { ... } Lies a function public Insert(item: E): void { ... } I construct a specific instance of my list const ...

Encountering a Circular JSON stringify error on Nest.js without a useful stack trace

My application is being plagued by this critical error in production: /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137 ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value ...

When it comes to TypeScript, there is a limitation in assigning a value to an object key with type narrowing through the

I created a function called `hasOwnProperty` with type narrowing: function hasOwnProperty< Obj extends Record<string, any>, Prop extends PropertyKey, >( obj: Obj, prop: Prop, ): obj is Obj & Record<Prop, any> { return Object ...

Inspect the TypeScript typings within Svelte documents directly from the terminal

When I run tsc --noemit, it successfully checks for type errors in the codebase. However, I have encountered an issue where it does not seem to check .svelte files. Is there a way to enable this functionality? I can see the type errors in .svelte files wh ...

Using React to map and filter nested arrays while also removing duplicates

Hello, I recently started working with react and I've encountered a challenge while trying to map an array. const fullMen = LocationMenuStore.menuItems['menu']['headings'].map((headings: any) => { <Typography>{ ...

Utilizing Typescript within Visual Studio Code alongside node_modules

I currently have typescript installed and am utilizing the powerful visual code editor. Whenever I attempt to navigate to the definition of a typescript function in the node_modules directory, Visual Studio Code ends up expanding the entire 'node_mod ...

Setting the desired configuration for launching an Aurelia application

After creating a new Aurelia Typescript application using the au new command from the Aurelia CLI, I noticed that there is a config directory at the root of the project. Inside this directory, there are two files: environment.json and environment.productio ...

Angular dynamic array binding binds to multiple elements rather than just one

In my code, I am working with an array object structured as follows: let myArray=[ { "id":"100", "child1":[ {"id":"xx","Array":[]}, {"id":"yy","Array":[]}, {"id":"zz","Array":[]} ] }, { "id":"200", "child1":[ {"id":"xx","Array ...

Unable to retrieve the updated value from the service variable

I'm attempting to implement a filter that allows me to search for items based on a service variable that is updated with user input. However, I am only able to retrieve the initial value from the service in my component. Service HTML (whatever is typ ...

Exploring the elements within the ContentChildren directive in Angular

Presenting my component: import { Component, OnInit, ContentChildren, QueryList } from '@angular/core'; import { IconBoxComponent } from '../icon-box/icon-box.component'; @Component({ selector: 'app-three-icon-box', temp ...