If you are a SharePoint Framework developer, you know that you never know what type of data you are going to get back from the SharePoint API. On one page, you can find a deeply nested value in the context object and the next, you get undefined somewhere in the chain. Take a look at the example below which gets a user’s Azure Active Directory id.
let addUserId: string = this.context.pageContext.aadInfo.userId._guid;
To get that guid value, any number of things could go wrong if context, pageContext, aadInfo, or userId happened to be undefined. If any of those have a value of undefined, it will throw an exception. Technically, that should never happen in this example, but you never know. In classic TypeScript, you might rewrite the statement like this to check for undefined.
let aadUserId: string = (this.context) && (this.context.pageContext) && (this.context.pageContext.aadInfo) && (this.context.pageContext.aadInfo.userId) ? this.context.pageContext.aadInfo._guid : undefined;
let aadUserId: string = this.context?.pageContext?.aadInfo?.userId?._guid;
Isn’t that so much cleaner? Almost life changing.
Optional chaining has been around in TypeScript since version 3.7. That’s great but the current version of SPFx at the time of writing is 1.11 and it uses TypeScript 3.3. You might think this would be an issue, but you can refer to this post from Andrew Connell to upgrade your version. In my experience, I ran into issues with TypeScript 3.8 and 3.9. However, TypeScript 3.7 works well with SPFx and I have been using it in a number of projects.
If you have been plagued by undefined values in your code, check out optional chaining. You can read more in the Mozilla documentation.