抛出新的类型错误或抛出类型错误



在Typescript中,抛出时使用new与不使用new有区别(TypeError)?

throw TypeError("some error here")

throw new TypeError("some error here")

这更像是一个JavaScript问题,而不是一个TypeScript问题。不,技术结果没有区别,两者都创建新的对象TypeError对象(规范中的详细信息)。当正常调用(不是通过new)时,Error和各种"本机"错误构造函数(TypeErrorReferenceError等)都将执行new调用(构造调用)而不是普通调用。

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

这是TypeScript操场上的相同代码,显示TypeScript将e1e2都视为TypeError类型。原因是TypeScript对TypeError的主要定义(lib.es5.d.ts)如下所示:

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

如您所见,它同时具有new(message?: string): TypeError;(构造函数调用返回TypeError)和(message?: string): TypeError;(正常调用返回TypeError)。


主观上,使用new对代码的读者来说更清楚,突出表明正在创建一个新对象。

相关内容

最新更新