Resolving deeply nested nullable values in Typescript using idx
Suppose you have a Typescript project with
strictNullChecks on, and a deeply nested type that you might get.
On account of
user.friends[n].languages[n].primary being null/undefined, trying to traverse through this structure without proper null checks would result in
Object is possibly 'undefined' compilation errors.
Doing deep null checks like this works, but is cumbersome, and doesn’t scale very well for readability:
Why not use non-null assertion?
The alternative is to use the non-null assertion, which lets us do
user.friends!!.languages!..., but if any path is null, this would
What about lodash.get?
get means well, but you use the type-safety. For an example, if you have this,
Typescript cannot infer the type of
firstFriendsLanguages automatically, and you completely exclude this expression from future type refactoring.
Idx works by evaluating the expression given in terms of a function in the second argument. If it
throws as a result of evaluating that function, idx will rescue that and just return
So, just to summarise, we make our accessor concise by using non-null assertions, and deflect the potential exception that might break our code by handling the excpetion (via idx).
It’s such a simple solution, that you should be able to implement the same utility in your codebase by following this file.
Originally published at nadeesha.github.io.