1.0.2 • Published 5 years ago

undefsafe-typed v1.0.2

Weekly downloads
289
License
ISC
Repository
github
Last release
5 years ago

undefsafe-typed

Build Status

Library to safely get subproperties of objects in typescript, without crashing if any child is undefined along the object tree. Inspired by undefsafe.

Fully supports types and inferres children types as return types.

Install:

yarn add undefsafe-typed

Usage:

interface IChild {
  name?: string;
  age?: number;
}
interface IMainObject {
  value?: string;
  children?: IChild[];
  someOtherNestedValue?: {
    a?: {
      b?: string;
    };
  };
}

const item = {
  name: 'item1',
  children: [{}, { name: 'John Doe', age: 21 }],
};

const name = undefsafe(item, 'name'); // name is inferred to string
const firstChildAge = undefsafe(item, 'children', 0, 'age'); // firstChildAge is inferred to number
const thirdChildAge = undefsafe(item, 'children', 3, 'age'); // thirdChildAge is inferred to number
const nestedB = undefsafe(item, 'someOtherNestedValue', 'a', 'b'); // is inferred to string

Dev and test

yarn install
yarn test