Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmutagorama/650a66d7917b1c8c6f777470c571d9b7 to your computer and use it in GitHub Desktop.
Save cmutagorama/650a66d7917b1c8c6f777470c571d9b7 to your computer and use it in GitHub Desktop.
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 && otherVal.prop.name;
// 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
user?.sayHello();
// making sure the function exists before executing it
user?.sayHello?.();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment