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. View Slide




  2. View Slide



  3. View Slide

  4. View Slide

  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

    View Slide


  6. View Slide

  7. https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Optional_chaining

    View Slide

  8. 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

    View Slide


  9. let expirationDate
    if (user.driverLicense) {
    expirationDate = user.driverLicense.expirationDate
    }

    View Slide

  10. View Slide

  11. View Slide



  12. https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-rc/

    View Slide

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

    View Slide


  14. "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;

    View Slide



  15. 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'

    View Slide



  16. $ npm i [email protected] ts-node
    $ npx ts-node

    View Slide

  17. View Slide