TypeScript 3.7 has been released with a few changes but one that we will focus on in this article is “Optional Operator”. It is elegant powerful and also simple to use.
The old way (Without Optional Operator)
From the snippet code, getPerson function might return undefined if the random number is an odd number. Therefore if you are going to use the return value of this function, without an optional operator you will have to do this.
This is quite hideous and it is quite annoying if you have to do this all the time. You might use lodash (_.get) operator to handle this case but that requires one more library.
Fortunately, now with Typescript 3.7, we have the optional operator. If you have been using Angular you might be familiar with this but if you are not, that’s fine. Let me explain it.
Basically, you just put ? (optional operator) after the variable or property or method that might be undefined or null then follow with . (dot).
Line 3: if maybePerson is null or undefined, it will stop there and return undefined otherwise it will return the value of maybePerson.name
Line 5: if maybePerson is an object but name is null or undefined, it will stop there and return undefined otherwise it will return the value of maybePerson.name.firstName
Line 9: if maybePerson is an object and name is an object but getFullName method is undefined, it will stop there and return undefined otherwise it will invoke getFullName method.
- The optional operator will always return undefined if the value we try to check is undefined or null.
- Other falsy values will not be caught by an optional operator (false, 0, empty string, NaN)
Reference: Typescript Official Website