Typescriptでオブジェクトのnullやundefinedの扱い方
なにも考慮せずに書くと、以下のコメント部分のようにコンパイラに怒られる。
type nullableObject = null | undefined | { hoge: string, foo?: Number }; const getObject = (): nullableObject => { return { hoge: "hogehoge" }; } const sampleObject = getObject(); console.log(sampleObject.hoge); // Object is possibly 'null' or 'undefined'.
ifでNullチェック
type nullableObject = null | undefined | { hoge: string, foo?: Number }; const getObject = (): nullableObject => { return { hoge: "hogehoge" }; } const sampleObject = getObject(); if (sampleObject != null) { console.log(sampleObject.hoge); } // "hogehoge"
Optional Chainingの?
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining
type nullableObject = null | undefined | { hoge: string, foo?: Number }; const getObject = (): nullableObject => { return { hoge: "hogehoge" }; } const sampleObject = getObject(); console.log(sampleObject?.hoge); // "hogehoge"
null または undefinedの場合
null
、undefined
いずれの場合も結果はundefined
type nullableObject = null | undefined | { hoge: string, foo?: Number }; const getObject = (): nullableObject => { return null; } const sampleObject = getObject(); console.log(sampleObject?.hoge); // undefined
fooを参照する場合
Nullish Coalescing
と組み合わせると設定されていない場合の初期値などを設定できる。
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing
type nullableObject = null | undefined | { hoge: string, foo?: Number }; const getObject = (): nullableObject => { return { hoge: "hogehoge", foo: 1 }; } const sampleObject = getObject(); console.log(sampleObject?.foo ?? 10); // 1
type nullableObject = null | undefined | { hoge: string, foo?: Number }; const getObject = (): nullableObject => { return null; } const sampleObject = getObject(); console.log(sampleObject?.foo ?? 10); // 10