Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Optional Chainingについて
Search
texdeath
October 08, 2019
Programming
3
170
Optional Chainingについて
TypeScript3.7にて導入される機能のひとつ、Optional Chainingについてのお話です。
texdeath
October 08, 2019
Tweet
Share
More Decks by texdeath
See All by texdeath
コードメトリクス計測による課題可視化と品質確保 / Visualize issues and ensure quality by measuring code metrics
texdeath
0
290
クライアントワークと管理画面の話
texdeath
0
180
次世代ヘッドレス開発室が提供するヘッドレスEC
texdeath
0
620
中期プロジェクトで e2eテストを導入してみて感じたこと
texdeath
2
7.7k
おさらいVue Composition API
texdeath
0
420
React使いがVueと仲良くなるためにやったこと
texdeath
0
270
副業として個人事業主をやる場合の メリット・デメリット
texdeath
0
100
Container Componentは必要なのか
texdeath
4
610
Kotlin/JSでReactアプリを作ってみた
texdeath
1
890
Other Decks in Programming
See All in Programming
How mixi2 Uses TiDB for SNS Scalability and Performance
kanmo
37
14k
苦しいTiDBへの移行を乗り越えて快適な運用を目指す
leveragestech
0
600
PHPカンファレンス名古屋2025 タスク分解の試行錯誤〜レビュー負荷を下げるために〜
soichi
1
200
『テスト書いた方が開発が早いじゃん』を解き明かす #phpcon_nagoya
o0h
PRO
2
260
責務と認知負荷を整える! 抽象レベルを意識した関心の分離
yahiru
3
540
PHPのバージョンアップ時にも役立ったAST
matsuo_atsushi
0
110
個人アプリを2年ぶりにアプデしたから褒めて / I just updated my personal app, praise me!
lovee
0
350
Amazon ECS とマイクロサービスから考えるシステム構成
hiyanger
2
560
法律の脱レガシーに学ぶフロントエンド刷新
oguemon
5
740
Djangoアプリケーション 運用のリアル 〜問題発生から可視化、最適化への道〜 #pyconshizu
kashewnuts
1
250
第3回 Snowflake 中部ユーザ会- dbt × Snowflake ハンズオン
hoto17296
4
370
color-scheme: light dark; を完全に理解する
uhyo
3
360
Featured
See All Featured
Building Adaptive Systems
keathley
40
2.4k
Rails Girls Zürich Keynote
gr2m
94
13k
Speed Design
sergeychernyshev
27
790
Designing Experiences People Love
moore
140
23k
A designer walks into a library…
pauljervisheath
205
24k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
PRO
12
960
Side Projects
sachag
452
42k
Improving Core Web Vitals using Speculation Rules API
sergeychernyshev
9
440
Writing Fast Ruby
sferik
628
61k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
30
4.6k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
248
1.3M
Learning to Love Humans: Emotional Interface Design
aarron
273
40k
Transcript
Optional Chaining について
自己紹介 Masatoshi Morita フロントエンドエンジニア 普段はReact / Vue / Node.js あたりを書いています
twitter: @texdeath
Agenda Optional Chaining とは~基本的な使い方 コード上の利点、コンパイル後 まとめ
Optional Chaining Object のプロパティ値参照で、プロパティの存在チェックを明示的に書かなくても処理し てくれる仕組み TC39 Proposals では現在Stage 3(Candidate) TypeScript
ではversion3.7 で先行的に導入(11 月リリース) 10/1 にbeta がリリースされており、playground でも試せる
基本的な使い方 存在しない可能性があるようなチェーンされたプロパティにアクセスする API の返却結果など、どのプロパティがRequired であるかについて保証がないようなオブ ジェクトの内容を操作する
定義ケース comment.author.name を定義したい type Comment = { type Comment =
{ message: string message: string author?: { author?: { name: string name: string detail?: string detail?: string } } }; }; declare const comment: Comment; declare const comment: Comment;
定義ケース name はプロパティとして存在していないかもしれないので、当然コンパイルエラーにな る // Object is possibly 'undefined'. //
Object is possibly 'undefined'. const name = comment.author.name; const name = comment.author.name;
アクセス方法・返り値 ? 演算子を使用して中間のプロパティにアクセスできる 返り値がなければ、undefined を返す 当然手前のプロパティが存在しない場合(chain が足りない)場合はコンパイルエラーに なる const name
= comment?.author?.name; const name = comment?.author?.name; // string | undefined // string | undefined console.log(name); console.log(name); const comment = { const comment = { message: "hoge" message: "hoge" }; };
関数呼び出しに対して使用する 関数呼び出しにも使用できる async function makeRequest(url: string, log?: (msg: string) =>
void) { async function makeRequest(url: string, log?: (msg: string) => void) { // log 関数が引数に渡されていれば実行する // log 関数が引数に渡されていれば実行する log?.(`Request started at ${new Date().toISOString()}`); log?.(`Request started at ${new Date().toISOString()}`); const result = (await fetch(url)).json(); const result = (await fetch(url)).json(); log?.(`Request finished at at ${new Date().toISOString()}`); log?.(`Request finished at at ${new Date().toISOString()}`); return result; return result; } }
コード上の利点 存在していないかもしれないプロパティにアクセスする際のガード節を除去できる null やundefined のチェックを書く必要がなく、より簡潔なコードを記述できる const name = (comment.author ===
null || comment.author === undefined) ? const name = (comment.author === null || comment.author === undefined) ? undefined : comment.author.name; undefined : comment.author.name; // ↓ // ↓ const name = comment?.author?.name; const name = comment?.author?.name;
Optional Chaining の論理演算子 comment.author.name の返り値が空文字だったとき、これらは同じ出力結果になる let name: string = "hoge";
let name: string = "hoge"; // ----- Logical operator ----- // ----- Logical operator ----- if (comment && comment.author && comment.author.name) { if (comment && comment.author && comment.author.name) { name = comment.author.name; name = comment.author.name; } } console.log(`name: ${name}`) console.log(`name: ${name}`) // ----- Optional chaining ----- // ----- Optional chaining ----- if (comment?.author?.name) { if (comment?.author?.name) { name = comment.author.name; name = comment.author.name; } } console.log(`name: ${name}`) console.log(`name: ${name}`)
Optional Chaining の論理演算子 厳密には論理AND はNaN や0 、false などのfalsy な値に特別に作用するので、Optional Chaining
でコンパイル後は出力結果が異なる Optional Chaining はコンパイル後、OR 演算子とvoid 演算子を使って評価している // ----- Logical operator( コンパイル後) ----- // ----- Logical operator( コンパイル後) ----- if (comment && comment.author && comment.author.name) { if (comment && comment.author && comment.author.name) { name = comment.author.name; name = comment.author.name; } } // ----- Optional chaining( コンパイル後) ----- // ----- Optional chaining( コンパイル後) ----- if ((_b = (_a = comment) === null || _a === void 0 ? void 0 : _a.author) === null || _b === if ((_b = (_a = comment) === null || _a === void 0 ? void 0 : _a.author) === null || _b === name = comment.author.name; name = comment.author.name; } }
所感 コード量が減って物理的に見通しが良くなるので、より直感的に書けそう ただ、既存の明示的なガード節がなくなるのはちょっと怖い・・・ 使うのであれば 同じくTypeScript3.7 で導入されるNullish Coalescing と組み合わせて、null のときはデ フォルト値にフォールバックするようにしたほうがよさそう
strictNullChecks は常時ON にしたほうがよさそう TypeScript 初心者なので、知見の強い人に意見を聞いてみたい
まとめ Optional Chaining を使えば楽にオプショナルなプロパティにアクセスできる コードも読みやすくなる でもコンパイルの時にすり抜けたりしたら怖いので、null チェック自体は厳密にしたほう が良い(と思う)
EOF