Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Typescript 3.7 introduced 2 amazing operators: Optional chaining and Nullish coalescing here's how to take advantage of them
// Before
const val = otherVal !== null && otherVal !== undefined && otherVal.prop !== null && otherVal.prop !== undefined &&;
// With optional chaining
const val = otherVal?.prop?.name;
const name = company.employees?.[0]?.name;
// let's say you want to return a undefined value, that's when nullish coalescring operator comes in handy.
const val = otherVal?.prop?.name ?? 'Anonymous';
const name = company.employees?.[0]?.name: 'User';
// Function invocation
// making sure user isn't nullish before executing the function
// making sure the function exists before executing it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment