TypeScript で Optional Chaining を使ってみた

TypeScript で Optional Chaining を使ってみた

998b440234ba4524a2c1ba1f130728f8?s=128

Masaki Koyanagi

October 25, 2019
Tweet

Transcript

  1. None
  2. • • •

  3. • •

  4. None
  5. 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
  6. https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Optional_chaining

  7. 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
  8. • let expirationDate if (user.driverLicense) { expirationDate = user.driverLicense.expirationDate }

  9. None
  10. None
  11. • ◦ https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-rc/

  12. https://devblogs.microsoft.com/typescript/ announcing-typescript-3-7-rc/ http://www.typescriptlang.org/play/

  13. • "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;
  14. • • 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'
  15. • • $ npm i typescript@rc ts-node $ npx ts-node

  16. None