Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

throw new TypeError or throw TypeError

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")

?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading