optional-chain brings optional chaining

optional-chain brings optional chaining

Property chaining is hard in JavaScript

img

Uncaught TypeError: Cannot read property ‘first’ of null

If you are JavaScript developer, I guess you’ve seen this TypeError than other errors. Also probably you’ve seen codes to avoid undefined access with checking if the property exists of not like below. Since JavaScript throws an error when accessing to a property value of undefined or null.

img

checking if name property is existing before accessing firstname

In addition, In the real world, there are many APIs usually return null or undefined values, so then checking a node existence before accessing to the property value is needed in everywhere.

To solve this problem, there is a proposal titled optional chaining for JavaScript for ECMAScript and the current status is stage1.

I hope we can use optional chaining syntax in the future but I also need this feature for now. So then I created a npm named optional-chain module to enable a similar functionality of optional chaining.

optional-chain

optional-chain is an optional chaining implementation in TypeScript. Technically, it uses Option Type to encapsulate original data. Here is an example how we can use this library.

img

Usage of optional-chain

optional-chain exports optional method which is a factory function to create Option instance. As you can see optionalUseris generated as Option instance. And .k method is an instance method to return a new Option instance which is narrowed by specified property. At the above example, referring to “first” property of “name” does not throw an exception, even “name” property is null.

img

Pick an element of an array with using .i function

For accessing an element of an array, you can use .i method, it also returns a new Option instance. And option-chain is always referring types of the object, so then if you are accessing a wrong property, You should see type error of TypeScript.

img

[ts] Argument of type ‘“foo”’ is not assignable to parameter of type ‘“name”’.

Here is an README of this module, you can check other APIs of option-chain. There are alsomatch API to express pattern matching and getOrElse API to return a default value when the instance doesn’t contain some value.

Credits && Conclusion

This library is highly inspired by lens.ts @utatti created. This library would not have been published without the idea. In the end, If you are tired to write && operator for guarding TypeError, optional-chain may be an option. Here is repo. Please let me know your feedback anytime.