TypeScript 3.7 is out and it is released with one of the most awaited features: Optional Chaining and Nullish Coalescing.
If you haven’t yet heard of TypeScript, it’s a language based on JavaScript that adds static type-checking along with type syntax.
Before we talk further, here is the list of the great features released in TypeScript 3.7.
- Optional Chaining
- Nullish Coalescing
- Assertion Functions
- Better Support for
never
-Returning Functions --declaration
and--allowJs
- (More) Recursive Type Aliases
- The
useDefineForClassFields
Flag and Thedeclare
Property Modifier - Build-Free Editing with Project References
- Uncalled Function Checks
- Flatter Error Reporting
// @ts-nocheck
in TypeScript Files- Semicolon Formatter Option
- Website and Playground Updates
- Breaking Changes
Optional Chaining is one of the most highly-demanded ECMAScript features. This one was filed over 5 years ago.
If you are an angular developer, you might have used the elvis (?) operator on the component template. which provides similar functionality on the template.
So what is optional chaining and why developers were eagerly waiting for this feature ?
Optional chaining lets us write code where we can immediately stop running some expressions if we run into a
null
orundefined
.
You can implement it by using the new ?.
operator
Let’s imagine we have an book
where the author
and the authors genres
might not be present in the data.
type Book = { title: string, author?: { name: string, description?: string, genres?: string[] } };
Now suppose you declare it with object book
.
declare const book: Book;
You can access the name
of the author
as below, Here currently we need to add an extra check to verify that book.author
is not null
or undefined
.
// Current Implementation : Without optional-chaining let author = book && book.author && book.author.name;
With optional chaining, you simplify this statement as below, You just need to add ?.
operator.
// Optional-Chaining let author = book?.author?.name;
TypeScript 3.7 has three different optional chaining variations.
Optional Property Access
Property access is via the .
operator. During property access, you can add optional chaining as we have seen in the above example, this is called optional property access.
Another example is :
// With Optional Property Access let x = foo?.bar.baz(); // Without Optional Property access let x = (foo === null || foo === undefined) ? undefined : foo.bar.baz();
Optional Element Access
Optional chaining also works with the []
operators when accessing elements.
const authorName= book?.["author"]?.["name"];
const genres = book?.author?.genres?.[0];
Optional Call
When dealing with functions which may or may not exist at runtime, optional chaining supports only calling a function if it exists. This can replace code where you would traditionally write something like:
if (func) func()
With optional chaining, you can simply write it as func?.();
For example, here is an optional call to the callback from an API request:
const callUpdateMetadata = (metadata: any) => Promise.resolve(metadata); // Fake API call const updateAlbumMetadata = async (metadata: any, callback?: () => void) => { await callUpdateMetadata(metadata); callback?.(); };
- Note
?.
acts differently than the &&
since &&
will act differently on “falsy” values (e.g. an empty string, 0, NaN, and, well, false).
Optional chaining will only take null
or undefined
as a signal to stop and return an undefined
.
Nullish Coalescing is another useful feature released in TypeScript 3.7
||
which returns the right-side expression if the left-side is null
or undefined
.
The issue with ||
with is, it considers empty string and 0 as a false. which is not true in all scenarios,
for example, if volume
is null
or undefined
use 0.5
as default volume.
let x = volume || 0.5;But the issue with
||
operator is if volume
is 0, x will become 0.5 which is not intended.
??
avoids some unintended behavior from0, NaN and ""
being treated as falsy values.
??
you can fix the above issue.
let x = volume ?? 0.5;
??
operator returns right side value only when left size value isnull
orundefined
.
In this article, we have seen the most awaited feature Optional Chaining & its variations and Nullish Coalescing.
I hope you like this article, please provide your valuable feedback and suggestions in below comment section🙂.
For more updates, Follow us 👍 on NgDevelop Facebook page.
If you use visual studio code editor then you might also like this article:Visual Studio Code tips and tricks