u936293
u936293

Reputation: 16224

Extending `Error` results in "only refers to a type, but is being used as a value here"

I have Typescript 4.0.2. In lib.es5.d.ts, there is the following fragment:

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 able to use const err = new Error("some message");

I want to extend Error to add a property named statusCode to handle Http errors. I tried:

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

But I am not able to use const e = new HttpException("Not found");. The error is 'HttpError' only refers to a type, but is being used as a value here. (ts2693)

Why can't HttpException be used in a similar manner to Error?

Upvotes: 1

Views: 1535

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37918

lib.es5.d.ts describes existing APIs (Error constructor in this case), but you're defining completely new one. Types/interfaces are erased at compile time hence the error. new keyword requires class or function that specifies the type of the object instance.

class HttpException extends Error {
    statusCode?: number
}

Playground

Upvotes: 1

Related Questions