2

Is there a way to overload the ? operator in Javascript to gracefully handle null or undefined.

An example use case is const userAddress = user?.address. userAddress is either some valid value or null/undefined.

If this is not possible in javascript, is it possible to overload the ? operator in any one of the languages that compile to javascript (ex. typescript).

David
  • 14,205
  • 20
  • 97
  • 144
  • https://github.com/tc39/proposal-optional-chaining – bugs May 10 '18 at 14:29
  • You can use the `&&`, https://stackoverflow.com/questions/49872267/null-coalescing-operator-in-react-js-typescript – Praveen Kumar May 10 '18 at 14:30
  • Exists in Coffee. Not yet there in TS. You can use Lodash get for that purpose. – Estus Flask May 10 '18 at 14:34
  • You cannot overload any operator in JavaScript. For that one specifically, "optional chaining" is coming to JavaScript soon so you can use [babel](https://dev.to/sammyisa/optional-chaining-may-be-coming-to-javascript--4ff0) to transpile. TypeScript itself is [waiting for a decision on the proposal from TC39](https://github.com/Microsoft/TypeScript/issues/16) before implementing it, since it doesn't want to stray away from JavaScript. – zeh Jan 14 '19 at 02:17

0 Answers0