在Typescript中,抛出时使用new与不使用new有区别(TypeError)?
throw TypeError("some error here")
和
throw new TypeError("some error here")
?
这更像是一个JavaScript问题,而不是一个TypeScript问题。不,技术结果没有区别,两者都创建新的对象TypeError
对象(规范中的详细信息)。当正常调用(不是通过new
)时,Error
和各种"本机"错误构造函数(TypeError
、ReferenceError
等)都将执行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将e1
和e2
都视为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
对代码的读者来说更清楚,突出表明正在创建一个新对象。