How can I solve the error 'TS2532: Object is possibly 'undefined'?

后端 未结 2 2085
小蘑菇
小蘑菇 2020-12-01 13:30

I\'m trying to rebuild a web app example that uses Firebase Cloud Functions and Firestore. When deploying a function I get the following error:

src/index.ts         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 13:58

    As of October 2019, optional chaining (the ? operator) is now available on TypeScript 3.7 (Beta). You may install that version by running the following command:

    npm install typescript@beta
    

    As such, you can simplify your expression to the following:

    const data = change?.after?.data();
    

    You may read more about it from the release notes, which cover other interesting features released on that version.

    Update (as of November 2019)

    TypeScript's optional chaining is now officially available. Installing the latest version of typescript should allow you to access the cool new features.

    npm install typescript
    

    That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

    const data = change?.after?.data() ?? someOtherData();
    

提交回复
热议问题