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.

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.