Safe nested object selector
safe-ts
helps you select values from nested objects and arrays,
without throwing error Cannot read property 'x' of undefined
.
It's compact, supported by all browsers, preserves Typescript typings and code-completion during development by your IDE (like WebStorm or Visual Studio Code).
It also takes an optional default value.
Install
npm i --save safe-ts
Requirements
- TypeScript >= 2.9
- NodeJS >= 6
Example Usage
; ; ; // 'C-0' ; // 'C-9'
Alternatives
Logical expressions are very verbose for long paths.
let c2 = (abc.a && abc.a.b && abc.a.b[9] && abc.a.b[9].c) || 'C-9'
Lodash
get(...)
is more compact,
but removes typescript support.
; ;
ts-optchain
preserves typescript typings and has an elegant syntax.
Unfortunately it requires Proxy.
Please consider this option if the browser support suits your project.
; ;
Reading the ts-optchain
source
and this article tought me a lot and inspired me to publish my simple alternative.
Type Preservation
safe-ts
preserves TypeScript typings and code-completion by IDEs like Visual Studio Code or WebStorm.
; ; console.logb.c // When typing 'b' your code editor suggests '.c'
Optional properties
To traverse optional properties, wrap your object in the all
function, included in ts-safe
.
; // Everything is optional.; ; // typescript error: Object is possibly 'undefined'; // no typescript error. e2 becomes undefined, as expected.
Note: the all
function tells typescript all (nested) properties exits.
This affects the return value. For instance, using abc
from before:
// 'all' tells typescript not to worry whether anything exists.; if c
Please keep this in mind when using optional properties.
License
safe-ts
is MIT Licensed.