# javascript 開発で出会った TypeError
期待された型以外に代入されると js がびっくりしてタイプエラー吐き出します。undefined と null の値でよく発生します。フロントエンド開発なら誰しも一度あったことがあると思いますが、TypeError のいろいろを調べてみました。
Mozilla TypeError についての説明 (opens new window)
TypeError エラーの原因
予期しない型があった
undefined または null の値でしばしば発生
エラーキャッチ
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.fileName); // "Scratchpad/1"
console.log(e.lineNumber); // 2
console.log(e.columnNumber); // 2
}
エラー生成
try {
throw new TypeError("Hello message", "someFile.js", 10);
} catch (e) {
console.log(e instanceof TypeError); // true
console.log(e.message); // "Hello message"
console.log(e.name); // "TypeError"
console.log(e.fileName); // "someFile.js"
console.log(e.lineNumber); // 10
console.log(e.columnNumber); // 0
}
# TypeError: Cannot read property '0' of undefined
console log に出たエラー
TypeError: Cannot read property '0' of undefined
at l.<anonymous> (6.ff9fb8e6.js:1)
at l.e._render (app.c2acb957.js:7)
at l.r (app.c2acb957.js:7)
at pn.get (app.c2acb957.js:7)
at new pn (app.c2acb957.js:7)
at e (app.c2acb957.js:7)
at l._n.$mount (app.c2acb957.js:7)
at init (app.c2acb957.js:7)
at app.c2acb957.js:7
at f (app.c2acb957.js:7)
該当ソース
{{ page.frontmatter && page.frontmatter.tags[0].toUpperCase() }}
修正後
{{
page.frontmatter &&
page.frontmatter.tags &&
page.frontmatter.tags[0].toUpperCase()
}}