TypeError

TypeError 对象表示无法执行操作时的错误,通常(但不限于)当值不是预期类型时。

¥The TypeError object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type.

在以下情况下可能会抛出 TypeError

¥A TypeError may be thrown when:

  • 传递给函数的操作数或参数与该运算符或函数期望的类型不兼容;or
  • 当尝试修改无法更改的值时;or
  • 当试图以不适当的方式使用某个值时。

TypeErrorserializable object,因此可以使用 structuredClone() 进行克隆,或者使用 postMessage()工人 之间进行复制。

¥TypeError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage().

TypeErrorError 的子类。

¥TypeError is a subclass of Error.

构造函数

¥Constructor

TypeError()

创建一个新的 TypeError 对象。

实例属性

¥Instance properties

还从其父级 Error 继承实例属性。

¥Also inherits instance properties from its parent Error.

这些属性在 TypeError.prototype 上定义并由所有 TypeError 实例共享。

¥These properties are defined on TypeError.prototype and shared by all TypeError instances.

TypeError.prototype.constructor

创建实例对象的构造函数。对于 TypeError 实例,初始值为 TypeError 构造函数。

TypeError.prototype.name

表示错误类型的名称。对于 TypeError.prototype.name,初始值为 "TypeError"

实例方法

¥Instance methods

从其父级 Error 继承实例方法。

¥Inherits instance methods from its parent Error.

示例

¥Examples

捕获类型错误

¥Catching a 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
}

创建类型错误

¥Creating a 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
}

规范

Specification
ECMAScript Language Specification
# sec-native-error-types-used-in-this-standard-typeerror

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also