TypeError
Baseline 广泛可用 *
TypeError 对象表示操作未能执行的错误,通常(但不仅限于)当值不是预期类型时。
当以下情况发生时,可能会抛出 TypeError:
- 传递给函数的运算数或参数与该运算符或函数预期的类型不兼容;或
- 尝试修改无法更改的值时;或
- 尝试以不适当的方式使用值时。
TypeError 是一个 可序列化的对象,因此可以使用 structuredClone() 进行克隆,或者使用 postMessage() 在 Workers 之间复制。
TypeError 是 Error 的子类。
构造函数
TypeError()-
创建一个新的
TypeError对象。
实例属性
还继承了其父级 Error 的实例属性。.
这些属性定义在 TypeError.prototype 上,并被所有 TypeError 实例共享。
TypeError.prototype.constructor-
创建实例对象的构造函数。对于
TypeError实例,初始值为TypeError构造函数。 TypeError.prototype.name-
表示错误的类型名称。对于
TypeError.prototype.name,初始值为"TypeError"。
实例方法
继承了其父级 Error 的实例方法。.
示例
捕获 TypeError
js
try {
null.f();
} catch (e) {
console.log(e instanceof TypeError); // true
console.log(e.message); // "null has no properties"
console.log(e.name); // "TypeError"
console.log(e.stack); // Stack of the error
}
创建 TypeError
js
try {
throw new TypeError("Hello");
} catch (e) {
console.log(e instanceof TypeError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "TypeError"
console.log(e.stack); // Stack of the error
}
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-native-error-types-used-in-this-standard-typeerror |
浏览器兼容性
加载中…