Home > OS >  throw new TypeError or throw TypeError
throw new TypeError or throw TypeError

Time:02-25

In Typescript is there a difference in using new or not when throwing (TypeError)?

throw TypeError("some error here")

and

throw new TypeError("some error here")

?

CodePudding user response:

This is more a JavaScript question than a TypeScript question. No, there's no difference in the technical result, both create new TypeError objects (details in the specification). When called normally (not via new), both Error and the various "native" error constructors (TypeError, ReferenceError, etc.) will perform a new call (a construct call) instead of a normal call.

const e1 = new TypeError("Error message here");
console.log(e1 instanceof TypeError); // true
console.log(e1.message);              // Error message here
const e2 = TypeError("Error message here");
console.log(e2 instanceof TypeError); // true
console.log(e2.message);              // Error message here

Here's that same code on the TypeScript playground, showing that TypeScript sees both e1 and e2 as being of type TypeError. The reason for that is that TypeScript's primary definition for TypeError (in lib.es5.d.ts) looks like this:

interface TypeError extends Error {
}

interface TypeErrorConstructor extends ErrorConstructor {
    new(message?: string): TypeError;
    (message?: string): TypeError;
    readonly prototype: TypeError;
}

declare var TypeError: TypeErrorConstructor;

As you can see, it has both new(message?: string): TypeError; (constructor call returning TypeError) and (message?: string): TypeError; (normal call returning TypeError).


Subjectively, using new is clearer to readers of the code, highlighting that a new object is being created.

  • Related