この記事は編集レビューを必要としています。ぜひご協力ください。
メッセージ
TypeError: "x" is (not) "y" Examples: TypeError: "x" is undefined TypeError: "x" is null TypeError: "undefined" is not an object TypeError: "x" is not an object or null TypeError: "x" is not a symbol
エラータイプ
何がうまくいかなかったのか?
予期しない型がありました。これは undefined
か null
の値でしばしば発生します。
また、Object.create()
や Symbol.keyFor()
のようなある種のメソッドは、特定の型を要求し、それを提供する必要があります。
例
有効なケース
// undefined と null の場合、substring メソッドは動作しません。 var foo = undefined; foo.substring(1); // TypeError: foo is undefined var foo = null; foo.substring(1); // TypeError: foo is null // ある種のメソッドは、特定の型が求められます。 var foo = {} Symbol.keyFor(foo); // TypeError: foo is not a symbol var foo = "bar" Object.create(foo); // TypeError: "foo" is not an object or null
問題を修正する
undefined
や null
への null ポインタを修正するには、たとえば typeof 演算子を使用できます。
if (typeof foo !== 'undefined') { // 今や foo が定義されていることが確認できており、使用できます。 }