Typescript error: The 'new' expression is missing a construct signature for its target, resulting in an implicit 'any' type

Here is a code snippet optimized for displaying custom errors in Chrome Devtools, Node.js, and other platforms. The inspiration for this came from this specific answer on StackOverflow.

function CustomErr (message) {
  var err = new Error(message)
  Object.setPrototypeOf(err, CustomErr.prototype)
  return err
}

CustomErr.prototype = Object.create(Error.prototype, {
  name: { value: 'Custom Error', enumerable: false }
})

However, when attempting to convert the code to Typescript:

function CustomErr (message: string) {
  var err = new Error(message)
  Object.setPrototypeOf(err, CustomErr.prototype)
  return err
}

CustomErr.prototype = Object.create(Error.prototype, {
  name: { value: 'Custom Error', enumerable: false }
})

Using

throw new CustomErr("something went wrong")
results in the following error message:

'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.ts(7009)

I am seeking guidance on how to properly annotate my code with types. Additionally, if you have an alternative solution that achieves the same behavior in Chrome DevTools, please share it. Thank you!

EDIT: It is important to note that I need to support older browsers, therefore ES6 classes cannot be used. Converting classes to ES6 is also not preferred due to the impact on the size of my lightweight library.

To summarize, how can I correctly add type annotations to the current code?

Answer №1

To create a class in TypeScript but implement it with a function, you can ensure that the output (the resulting JavaScript) remains unaffected while allowing TypeScript to recognize the CustomErr as a "newable":

declare class CustomErr extends Error {
    constructor(message: string);
}

function CustomErr(message: string) {
    var err = new Error(message)
    Object.setPrototypeOf(err, CustomErr.prototype)
    return err
}

CustomErr.prototype = Object.create(Error.prototype, {
    name: { value: 'Custom Error', enumerable: false }
})

throw new CustomErr("something went wrong") // no error now

Interactive Example

Answer №2

To incorporate custom error handling in TypeScript, I followed these steps:

interface CustomError {
    code: number;
    message: string;
}

export const CustomError = (function (this: CustomError, code: number, message: string) {
    this.code = code;
    this.message = message;
} as unknown) as { new (code: number, message: string): CustomError };

With this setup, I can now utilize custom errors throughout my codebase:

throw new CustomError(403, 'A specific error message');

I can also handle them within asynchronous functions like so:

export const ProcessData = async ({ inputData }: { inputData: string }): Promise<string> => {
    try {
        // some asynchronous operations

        throw new CustomError(403, 'Encountered an issue while processing data');
    } catch (error) {
        return Promise.reject(error);
    }
};

Answer №3

Even though I'm still unsure about annotating my code, a simple modification from throw new CustomErr('err') to throw CustomErr('err') resolved the issue at hand. It seems that while JavaScript permits the use of the new constructor, TypeScript does not.

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 testing nested HTTP calls in unit tests

I am currently in the process of unit testing a function that looks like this: async fetchGreatHouseByName(name: string) { const [house] = await this.httpGetHouseByName(name); const currentLord = house.currentLord ? house.currentLord : '957'; ...

Interfacing Node JS with Java Web Services via SOAP

I've been attempting to connect Java web services from a Node.js module, but I'm encountering an error in the wsdl library. Below is my wsdl file: <!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130 ...

unable to retrieve / interpret data from herdsmen using fetch

When sending a request to a node server, the server responds with headers and a blank body. Despite being able to view the headers in the network activity panel within dev-tools, I faced difficulties reading them using the following code: let uploaded ...

Requesting Google Docs data from different domains in Internet Explorer 9

While working on retrieving data from a Google Doc spreadsheet using Angular's $http, everything seems to be functioning well except for a cross-domain issue with IE9. An 'Access is denied' Error keeps popping up. Below is the code snippet ...

Experiencing difficulties launching my Server.JS due to a listening error

Hey there, I'm struggling to get my server.js up and running. Whenever I try to run node on it, I keep getting the error message "listening on *:3000". Below is the code for my server.js: var app = require('express')(); var http = require(&a ...

Using a constructor function in a for loop

Currently, I am learning how to build a Blackjack game with Javascript on Codecademy. I'm struggling to figure out what code to write inside the for-loop. The task at hand is to create a "score" method within the Hand constructor. This method should ...

The function chrome.cookies.get is returning undefined or causing an error to be thrown

chrome.cookies.get({url:"http://www.dahotre.com", name:"userid"}, function(){}) returns undefined when checked in the console. If I exclude the optional empty function(), it raises an error. chrome.cookies.get({url:"http://www.dahotre.com", name:"userid"} ...

Passing an array through ajax from PHP to JavaScript using a properly formatted JSON structure

I began with an array generated by PHP and retrieved via ajax, which had the following structure: Array ( [0] => {id:"12",from:"09:00:00",to:"15:00:00"} [1] => {id:"13",from:"08:00:00",to:"10:00:00"} [2] => {id:"12",from:"15:00:00",to ...

Tips for patiently waiting for a method to be executed

I have encountered a situation where I need to ensure that the result of two methods is awaited before proceeding with the rest of the code execution. I attempted to use the async keyword before the function name and await before the GetNavigationData() me ...

Error in TypeScript when utilizing an Enum as a string

Attempting to include a string enum in my Angular 2 project resulted in an error during the npm project startup: ERROR in e:/projects/dbtool-fullstack/dbtool-client/src/app/shared/models/full-m odels/enums/Sex.ts (2,10): Type '"Male"' is not ass ...

When aot is enabled, ngClass and ngIf condition may not compile successfully

I am encountering an issue with a div using ngClass and ngIf conditions: <div [ngClass]="{ 'active': nbActive === 1 }" > <!-- some stuff --> </div> There is also a similar div using a ngIf condition: <div *ngIf="nbActi ...

What are some ways to direct users from one page to another without relying on server-side programming?

Is there a way to create a redirect page using jQuery or JavaScript? What is the process of writing client-side scripting code to redirect the browser from one page (page1) to another page (page n)? ...

Checking the successful loading of JSON data in Angular2+ by following these steps:

I am struggling to write a test for an Angular method that loads the contents of a locally stored JSON file featuring an array. test.ts (trimmed for brevity) describe('MyComponent', () => { beforeEach(async(() => { TestBed.configureT ...

Tips for refreshing data in BigQuery following an onUpdate occurrence

Currently, I am successfully importing data from Firebase to BigQuery using the onWrite event and the table.insert function. However, I am facing an issue when trying to update data in BigQuery on the onUpdate event as the table.update function is not av ...

Strategies for avoiding a hover component from causing distortion to its parent component in React

I am encountering an issue with a hover component that is causing distortion in its parent component when displayed. Essentially, I need to prevent the hover component from affecting the layout of its container. Below is the code snippet: Styling for Lang ...

Unable to locate the accurate information

Every time I run the cycle, there should be a match with the specified parameters and the message "OK" should appear. However, I am always getting a result of "No". request( { url: 'http://localhost:5000/positions/get', metho ...

Guide to updating information inside of script tags in html using javascript

Within my HTML, there is a script tag that looks like this: <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "VideoObject", "name": "Title", "description": "Video descrip ...

Issues have been observed with the functionality of the Node.js EventEmitter when attempting to

Here's the issue: I have a class called save.js that inherits from EventEmitter. Here's how it looks: var util = require('util'); var EventEmitter = require('events').EventEmitter; var save = function(pdf){ var ...

Creating interactive forms - Incorporating dynamic checkbox options within the expansion panel element

Recently, I developed a basic movie list app with a checkbox list for genre filtering. Initially, I managed to achieve the desired functionality without using reactive forms. However, I am now exploring implementing the same functionality using reactive ...

Discover the highest value within a JSON object and save it as a variable

I am working on a d3 graph with a specified Y-axis range in my code: var yScale = d3.scaleLinear() .domain([0, 1]) // input .range([height, 0]); // output However, I have realized that a scale of 0 to 1 may not be the most suitable for my data. ...