类型错误:"x" 是(不是)"y"
当存在意外类型时,会发生 JavaScript 异常 "x 是(不是)y"。通常,会出现意外的 undefined
或 null
值。
¥The JavaScript exception "x is (not) y" occurs when there was an
unexpected type. Oftentimes, unexpected undefined
or null
values.
信息
¥Message
TypeError: Cannot read properties of undefined (reading 'x') (V8-based) TypeError: "x" is undefined (Firefox) TypeError: "undefined" is not an object (Firefox) TypeError: undefined is not an object (evaluating 'obj.x') (Safari) TypeError: "x" is not a symbol (V8-based & Firefox) TypeError: Symbol.keyFor requires that the first argument be a symbol (Safari)
错误类型
什么地方出了错?
¥What went wrong?
有一种意想不到的类型。对于 undefined
或 null
值,这种情况经常发生。
¥There was an unexpected type. This occurs oftentimes with undefined
or
null
values.
此外,某些方法(例如 Object.create()
或 Symbol.keyFor()
)需要必须提供的特定类型。
¥Also, certain methods, such as Object.create()
or
Symbol.keyFor()
, require a specific type, that must be provided.
示例
无效案例
¥Invalid cases
你不能对 undefined
或 null
变量调用方法。
¥You cannot invoke a method on an undefined
or null
variable.
const foo = undefined;
foo.substring(1); // TypeError: foo is undefined
const foo2 = null;
foo2.substring(1); // TypeError: foo2 is null
某些方法可能需要特定类型。
¥Certain methods might require a specific type.
const foo = {};
Symbol.keyFor(foo); // TypeError: foo is not a symbol
const foo2 = "bar";
Object.create(foo2); // TypeError: "foo2" is not an object or null
解决问题
¥Fixing the issue
要将空指针修复为 undefined
或 null
值,可以先测试该值是 undefined
还是 null
。
¥To fix null pointer to undefined
or null
values, you can test if the value is undefined
or null
first.
if (foo !== undefined && foo !== null) {
// Now we know that foo is defined, we are good to go.
}
或者,如果你确信 foo
不会是像 ""
或 0
这样的另一个 falsy 值,或者如果过滤掉这些情况不是问题,你可以简单地测试其真实性。
¥Or, if you are confident that foo
will not be another falsy value like ""
or 0
, or if filtering those cases out is not an issue, you can simply test for its truthiness.
if (foo) {
// Now we know that foo is truthy, it will necessarily not be null/undefined.
}