r/javascript • • Feb 20 '18

Optional Chaining may be coming to JavaScript

https://dev.to/sammyisa/optional-chaining-may-be-coming-to-javascript--4ff0
321 Upvotes

100 comments sorted by

View all comments

18

u/[deleted] Feb 20 '18 edited Feb 20 '18

I need this in my life today. I'd say undefined is the biggest annoyance and probably the only major one remaining I have with Javascript. Currently using lodash get for this purpose.

Edit: wanted to expand why lodash get is not good enough for me. I don't mind using library but lodash get doesn't work with TypeScript well.

3

u/calligraphic-io Feb 20 '18

Have you looked at using algebraic data types, like Sanctuary.js?

3

u/[deleted] Feb 20 '18

No.

0

u/0987654231 Feb 20 '18

It's worth looking at, algebraic data types(ADTs) can be a powerdul too.

1

u/Auride Feb 20 '18

I don't imagine it would be particularly hard to implement a TS equivalent yourself, just for this purpose. At least the array variation is pretty simple:

function get(
  objectToAccess:Object,
  path:Array<string|symbol>,
  defaultValue:any = undefined
):any{
  let objUnshelled = objectToAccess;
  for (const key of path) {
    const nextObj = objUnshelled[key];
    if (nextObj === undefined) {
      return defaultValue;
    } else {
      objUnshelled = nextObj;
    }
  }
  return objUnshelled;
}

The string variants are slightly more complicated, but it probably reduces down to applying String.split() and maybe another parse step or two to handle array indexing.

1

u/[deleted] Feb 20 '18

I'm not sure what your function solves. Lodash has TypeScript definitions. The issue is second parameter being string. So you any use autocompletion and it's prone to errors and refactoring is not available either. You also have to cast type. In short, it sucks compared to proposed native way.

1

u/[deleted] Feb 20 '18

With TypeScript I'm using those solutions:

Use _.get instead of _.has:

_.get(myObject, "key.subkey", <any_default_value_if_property_does_not_exist>)

If you need to use _.has, use the exclamation mark operator in TypeScript to tell the compiler that those keys exist.

if (_.has(myObject, "key.subkey")){
	myObject!.key!.subkey = "foo";
}

But yeah you need to force the type if the interface of the object wasn't created.