safe-ts
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

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

import { safe } from 'safe-ts';
 
const abc = {
    a: {
        b: [
            {c: 'C-0'}, 
        ],
    }
};
 
let c1 = safe(_=> abc.a.b[0].c); // 'C-0'
 
let c9 = safe(_=> abc.a.b[9].c, 'C-9'); // '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.

import { get } from 'lodash';
 
let c9 = get(abc, 'a.b[9].c', 'C-9');

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.

import { oc } from 'ts-optchain';
 
let c9 = oc(abc).b.c('C-9');

Reading the ts-optchainsource 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.

const abc = {a: {b: {c: 'C'}}};
 
let b = safe(_=> abc.a.b, {c:'C default'});
 
console.log(b.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.

import { safe, all } from 'safe-ts';
 
// Everything is optional.
type ABCDE = {a?: {b?: {c?: {d?: {e?: string}}}}}
const abc:ABCDE = {
    a:{
        b: {
            c: {} // incomplete.
        }
    }
};
 
let e1 = safe(_=> abc.a.b.c.d.e); // typescript error: Object is possibly 'undefined'
let e2 = safe(_=> all(abc).a.b.c.d.e); // 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.
let c = safe(_=> all(abc).a.b.c);
 
if (c) {
    // When c exists, typescript falsely assumes d and e exist.
    console.log(c.d.e); // RUNTIME error: Cannot read property
    
    // This works. Typscript normally enforces this. Now it's up to you. 
    if (c.d) {
        console.log(c.d.e);
    }
}

Please keep this in mind when using optional properties.

License

safe-ts is MIT Licensed.

Package Sidebar

Install

npm i safe-ts

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

38.6 kB

Total Files

12

Last publish

Collaborators

  • vddrift