A typesafe way to access nested properties through potentially-undefined parent properties, while we wait for the optional chaining ?. operator to finally exist and get real TypeScript support.

With typesafe-get, the below TypeScript code will work, without no compile or runtime errors, for all valid values of input :

; ;

All parameters are validated as properties at the relevant level, and the return type will always be finalPropType | undefined (the type of the property at the very last level, or undefined).

If at any point while following the chain you attempt to follow a path through an undefined object then undefined is immediately returned, and you'll never see the dreaded Cannot read property '<something>' of undefined exception. It works with simple iteration over the property names provided, no crazy (and expensive) try/catch magic here.

Install it

npm install --save typesafe-get

Use it

This module ships with TypeScript types, and is built in JS for UMD, so you should be able to immediately start using it in many environments with no further setup.

With some webpack configurations, you'll need to explicitly allow requiring UMD modules. To do that you can use UMD-Compat-Loader, like so:

module : { rules : [ { test : / node_modules [ \\ |/ ] typesafe-get / , use : { loader : ' umd-compat-loader ' } } ] }

The get function is exported as both a property and the default export of this module. That means importing looks like:

import { get } from ' typesafe-get ' ; import get from ' typesafe-get ' ;

To use get :

get ( obj , ' aPropertyKey ' ) ; get ( obj , ' key1 ' , ' key2 ' ) ; get ( obj , ' key1 ' , ' key2 ' , ' key3 ' , ' key4 ' , ' key5 ' ) ; get ( array , 0 , ' key1 ' ) ;

Each parameter name is checked against the valid parameter names at that level (so a parameter name that definitely doesn't exist will be caught by TS).

The return type will be automatically inferred as the type the final parameter would have, if the whole chain is defined, or undefined .

get itself supports up to 5 property parameters max. If you really truly honestly need more than that, take a good hard look at yourself, and then feel free to open a PR - it should be fairly easy to see how to extend the types to support more. But only if you're really sure you need this. Seriously, what are you doing that makes this a good idea.

Contributing

Have a bug? File an issue with a simple example that reproduces this so we can take a look & confirm.