オプショナルチェーン (optional chaining)
JavaScriptのオプショナルチェーン?.は、オブジェクトのプロパティが存在しない場合でも、エラーを起こさずにプロパティを参照できる安全な方法です。
プロパティ参照がエラーになる問題
JavaScriptではnullやundefinedのプロパティを参照するとエラーが発生します。
jsconstbook =undefined ;consttitle =book .title ;constauthor = null;constauthor .
jsconstbook =undefined ;consttitle =book .title ;constauthor = null;constauthor .
エラーを避けるには、値がnullやundefinedでないかチェックする必要があります。
jsconstbook =undefined ;consttitle =book === null ||book ===undefined ?undefined :book .title ;console .log (title );
jsconstbook =undefined ;consttitle =book === null ||book ===undefined ?undefined :book .title ;console .log (title );
jsconstbook = {title : "サバイバルTypeScript" };consttitle =book === null ||book ===undefined ?undefined :book .title ;console .log (title );
jsconstbook = {title : "サバイバルTypeScript" };consttitle =book === null ||book ===undefined ?undefined :book .title ;console .log (title );
ネストしたオブジェクトの場合、チェック処理はいっそう複雑になってきます。
jsconstbook = {author : {constauthorEmail =book === null ||book ===undefined ?undefined :book .author === null ||book .author ===undefined ?undefined :book .author .
jsconstbook = {author : {constauthorEmail =book === null ||book ===undefined ?undefined :book .author === null ||book .author ===undefined ?undefined :book .author .
チェックすればエラーなく動きますが、記述量が多くなるという課題もあります。
オプショナルチェーン
JavaScriptのオプショナルチェーンはnullやundefinedのプロパティを誤って参照しないようにしつつ、記述量を抑えられる書き方です。オプショナルチェーンは?.演算子を用いて書きます。
jsconstbook =undefined ;consttitle =book ?.title ;// ^^オプショナルチェーンconsole .log (title );
jsconstbook =undefined ;consttitle =book ?.title ;// ^^オプショナルチェーンconsole .log (title );
jsconstbook = {title : "サバイバルTypeScript" };consttitle =book ?.title ;console .log (title );
jsconstbook = {title : "サバイバルTypeScript" };consttitle =book ?.title ;console .log (title );
オプショナルチェーンはネストして使うこともできます。
jsconstbook =undefined ;constauthorEmail =book ?.author ?.console .log (authorEmail );
jsconstbook =undefined ;constauthorEmail =book ?.author ?.console .log (authorEmail );
jsconstbook = {author : {constauthorEmail =book ?.author ?.console .log (authorEmail );
jsconstbook = {author : {constauthorEmail =book ?.author ?.console .log (authorEmail );
もしも?.に先行する変数やプロパティの値がnullまたはundefinedのときは、その先のプロパティは評価されず、undefinedが返ります。
jsconstbook = null;console .log (book ?.title );
jsconstbook = null;console .log (book ?.title );
jsconstbook = {author : null };console .log (book .author ?.name );
jsconstbook = {author : null };console .log (book .author ?.name );
関数呼び出し
関数を呼び出すときにもオプショナルチェーンが使えます。関数に使う場合は、引数カッコの前に?.を書きます。
jsconstincrement =undefined ;constresult =increment ?.(1);console .log (result );
jsconstincrement =undefined ;constresult =increment ?.(1);console .log (result );
jsconstincrement = (n ) =>n + 1;constresult =increment ?.(1);console .log (result );
jsconstincrement = (n ) =>n + 1;constresult =increment ?.(1);console .log (result );
メソッドを呼び出すときも同様の書き方です。
jsconstbook = {getPrice :undefined };console .log (book .getPrice ?.());
jsconstbook = {getPrice :undefined };console .log (book .getPrice ?.());
jsconstbook = {getPrice () {return 0;},};console .log (book .getPrice ?.());
jsconstbook = {getPrice () {return 0;},};console .log (book .getPrice ?.());
配列要素の参照
配列要素を参照する際にもオプショナルチェーンが使えます。要素を参照する場合は、カギカッコの前に?.を書きます。
jsconstbooks =undefined ;consttitle =books ?.[0];console .log (title );
jsconstbooks =undefined ;consttitle =books ?.[0];console .log (title );
jsconstbooks = ["サバイバルTypeScript"];consttitle =books ?.[0];console .log (title );
jsconstbooks = ["サバイバルTypeScript"];consttitle =books ?.[0];console .log (title );
TypeScriptでの型
TypeScriptでオプショナルチェーンを使った場合、得られる値の型は、最後のプロパティの型とundefinedのユニオン型になります。
tsletbook : undefined | {title : string };consttitle =book ?.title ;
tsletbook : undefined | {title : string };consttitle =book ?.title ;
TypeScriptのコンパイル結果
TypeScriptのコンパイラーオプションtargetがes2020以上のときは、オプショナルチェーンはそのままJavaScriptにコンパイルされます。
tsconst title = book?.title;
tsconst title = book?.title;
targetがes2019以前の場合は、次のような三項演算子を用いたコードにコンパイルされます。
tsconst title = book === null || book === void 0 ? void 0 : book.title;
tsconst title = book === null || book === void 0 ? void 0 : book.title;
Null合体演算子と組み合わせる
オプショナルチェーンがundefinedを返したときに、デフォルト値を代入したい場合があります。その際には、Null合体演算子??を用いると便利です。
jsconstbook =undefined ;consttitle =book ?.title ?? "デフォルトタイトル";console .log (title );
jsconstbook =undefined ;consttitle =book ?.title ?? "デフォルトタイトル";console .log (title );
学びをシェアする
・JavaScriptのオプショナルチェーン?.は安全にプロパティを参照する方法
・値がnullかundefinedのときundefinedが返る
・a?.b?.cのようにネストも可能
・関数は?.()
・配列は?.[]
・TypeScriptでは値の型とundefinedのユニオン型になる
・Null合体演算子と相性がいい
『サバイバルTypeScript』より
関連情報
📄️ 配列要素へのアクセス
JavaScriptでの配列要素アクセス
📄️ 三項演算子
JavaScriptの三項演算子(ternary operator)は、条件分岐ができる演算子です。条件式、真の場合の値、偽の場合の値の三項を取るため三項演算子と呼ばれています。