Creating a subclass of `Error` leads to the error message "only refers to a type, but is being used as a value here."

I currently have Typescript 4.0.2 installed. Within lib.es5.d.ts, there is the snippet provided below:

interface Error {
    name: string;
    message: string;
    stack?: string;
}

interface ErrorConstructor {
    new(message?: string): Error;
    (message?: string): Error;
    readonly prototype: Error;
}

declare var Error: ErrorConstructor;

I am successfully using

const err = new Error("some message");

My goal is to enhance the Error interface by adding a property named statusCode specifically for handling Http errors. I attempted the following:

interface HttpException extends Error {
  // new(message?: string): Error;
  // (message?: string): HttpException;
  // readonly prototype: HttpException;
  statusCode?: number
}

However, I encountered an issue when trying to use

const e = new HttpException("Not found");
. The error message stated
'HttpError' only refers to a type, but is being used as a value here. (ts2693)

Why can't HttpException be utilized in the same way as Error?

Answer №1

lib.es5.d.ts outlines the current APIs, particularly focusing on the Error constructor. However, in this context, you are introducing a brand new API. Due to type erasure during compilation, the error arises. The use of the new keyword necessitates a class or function that defines the object instance's type.

class HttpException extends Error {
    statusCode?: number
}

Interactive Demo

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

Encountering an Angular 13 ChunkLoadError during application deployment, despite the presence of the respective chunk

We encountered an issue with our application's upgrade from Angular 11 to 13. While running 'ng serve' on the local machine works fine, deploying it to our Azure app service causes the lazy loaded modules to fail loading. The specific error ...

Is it feasible to implement early-return typeguards in Typescript?

There are instances where I find myself needing to perform type checks on variables within a function before proceeding further. Personally, I try to minimize nesting in my code and often utilize early-return statements to keep the main functionality of a ...

Showcasing a selection of items from an array using Angular

I'm struggling with a particular implementation. I have an array filled with objects, and I only want to display the "name" property of those objects in a dropdown menu. When a user selects an option, I would like to access the entire object. Is this ...

Having trouble resolving the typescript package while integrating with another module

Attempting to develop a basic npm package with TypeScript and bundle it using webpack. When trying to use the package in another module, such as a react application named 'module A.' Within module A, the 'myLibrary' package is installe ...

Learn to extract metadata from a gRPC service function using Node.js

Currently, my gRPC service is up and running with the following setup: server.addService(PassportService, implementation); server.bind(mfeConfig().grpc.passport, grpc.ServerCredentials.createInsecure()); server.start(); To call this service from a client ...

What are the recommended TypeScript tsconfig configurations for running Node.js 10?

Can someone provide information on the necessary target/libs for enabling Node.js v10.x to utilize async/await without generators? I have found plenty of resources for node 8 but not as much for node 10. ...

Generating a fresh instance of input value in Angular2

In the hierarchy of components, I have a grand parent component where I am passing the "selectedValue" to the parent component like so: @Component({ selector: 'grand-parent', template: '<parent [details]="selectedValue" ></par ...

Struggling with sluggish performance on a certain project within VS Code

My experience with VS code has been excellent over the years, but I recently encountered a problem in one of my projects that caused a significant slowdown in performance. Strangely, other projects are working fine without any issues on VS code. I suspect ...

Numerous attributes housed within a single element

In my project, I have set up a Store using Angular and NgRx 13. Within my SharedModule, I define components including selectors which load content into the store to prevent redundant API calls. https://i.stack.imgur.com/sr3nl.png This approach is impleme ...

Utilizing Sequelize to search for existing items or create new ones in a list

My experience with sequelize is limited and I am having trouble understanding certain aspects. Despite my efforts to search for more information, I couldn't find anything specific that addresses my confusion. // API Method function SeederApi(req: Req ...

How can I verify the value of a class variable in TypeScript by using a method?

I need a more concise method to inform TypeScript that my client has been initialized (no longer null). While I have achieved this functionality, the current implementation seems unnecessarily verbose. Here is how it currently looks: export abstract class ...

Is it necessary to use useCallback when executing a function from a child component?

Consideration should be given to using useCallback when ensuring referential equality during parent component renders. However, it's unclear if this is necessary in a scenario where the parent is dealing with a child function. import { ReactNode, useC ...

Submitting an image blob to a database using the FormBuilder

I'm facing an issue with uploading a file blob into the same DB as my form. Here is my form: this.accForm = this.formBuilder.group({ team_leader: ['', Validators.required], hotel_name: ['', Validators.required], address: [&a ...

Bringing in AuthError with TypeScript from Firebase

Is it possible to verify if an error is of type "AuthError" in TypeScript when using Firebase? I have a Https Callable function with a try/catch block that looks like this: try { await admin.auth().getUser(data.uid); // will throw error if user doesn& ...

Make sure the task is completed before proceeding any further

Before proceeding to other functions, it is crucial that my service is completed as I rely on its result. Despite trying various solutions, such as this one, I have not been successful. Here is an example of the code: The service being used: getText( ...

Is there a way to validate an input field and display error messages using a TypeScript file instead of directly in the HTML file within Angular 4?

I am just starting out with Angular, so please bear with me if my question seems basic. I'm eager to learn and hopeful that I can find the answers I need here. Currently, I have implemented validation for an input field that captures a user's Fi ...

Ng2-NoUISlider displaying consistent range values

I'm facing an issue with implementing multiple sliders on a single page where each slider should have different range values. Here is a snippet of my HTML: <div *ngFor="let property of comepleteFilters"> <h5>{{property.pro ...

Choosing the correct key and handling parsing errors

As I work on converting a class component to TypeScript, I encountered an error while trying to implement one of my onChange methods. The error message stated: "Argument of type '{ [x: number]: any; }' is not assignable to parameter of type &ap ...

Ways to verify the presence of my property within a specific type

When it comes to TypeScript, we have the ability to declare partial types. But what happens when we need to check if a property is within the keys of a type? Let's explore. interface Car { Brand: string; Model: string; } type KeyofCar = keyof ...

Tips for Modifying the currentUrl identifier in Angular 2

I am trying to change the ID property of my currentUrl object within my component. My goal is for the ID to update and then fetch the corresponding data based on that ID. However, I keep encountering this error message: "Cannot assign to read only propert ...