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
?
HttpException
is only an interface.Error
is a concrete object.declare var Error: ErrorConstructor;
makes sure TS knows that. – VLAZError
a concrete object? What do the three lines inErrorConstructor
mean? – Old Geezernew
with it.HttpException
is just an interface, it defines the public API of an object but supplies no implementation for them. That's also what the three lines inErrorConstructor
define - the public interface. In that case, it says that you can call it withnew
(which takes an optional parameter), or call it as a function withoutnew
(also takes an optional parameter), finally there is aprototype
property. – VLAZ