Upgrade to Pro — share decks privately, control downloads, hide ads and more …

TypeScript で Optional Chaining を使ってみた

TypeScript で Optional Chaining を使ってみた

Masaki Koyanagi

October 25, 2019
Tweet

More Decks by Masaki Koyanagi

Other Decks in Programming

Transcript

  1. const user1 = { age: 26, driverLicense: { expirationDate: '2023/01/22'

    }, } const user2 = { age: 12, driverLicense: null, } user1.driverLicense.expirationDate // '2023/01/22' user2.driverLicense.expirationDate // TypeError: Cannot read property 'expirationDate' of null
  2. const user1 = { age: 26, driverLicense: { expirationDate: '2023/01/22'

    }, } const user2 = { age: 12, driverLicense: null, } user1.driverLicense?.expirationDate // '2023/01/22' user2.driverLicense?.expirationDate // undefined
  3. • "use strict"; var _a, _b; const foo = {

    bar: null }; // foo?.bar?.baz (_b = (_a = foo) === null || _a === void 0 ? void 0 : _a.bar) === null || _b === void 0 ? void 0 : _b.baz;
  4. • • const foo = { items: ['Pen', 'Pineapple', 'Apple'],

    get bar() { console.count('bar!'); return { baz: this.items.join() }; } } foo?.bar?.baz // bar!: 1 // 'Pen,Pineapple,Apple' foo && foo.bar && foo.bar.baz // bar!: 2 // bar!: 3 // 'Pen,Pineapple,Apple'