Last active
January 31, 2021 12:16
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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