在类型记录中,当抛出时(TypeError)使用新的还是不使用的有区别吗?
throw TypeError("some error here")
和
throw new TypeError("some error here")
发布于 2022-02-25 10:04:00
这与其说是一个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
类型。其原因是,类型记录的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
,突出显示正在创建一个新对象。
https://stackoverflow.com/questions/71264117
复制相似问题