jednano / get

Type-safe get function returns a nested value from an object.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

@jedmao/get

NPM version npm license Travis Build Status codecov BundlePhobia Minified BundlePhobia Minified + gzip code style: prettier Unicorn Approved

npm

Type-safe get function returns a nested value from an object.

Types will be preserved up to 10 levels deep. After that, things start coming back as any. This is due to a depth limitation of TypeScript.

This library is tiny BundlePhobia Minified + gzip, despite how big it might look if you see the TypeScript source code. Most of what you see is type information, which disappears when compiled into JavaScript, but provides rich in-editor support (see below).

screenshot

Installation

npm i @jedmao/get

Usage

import get from '@jedmao/get'

const data = {
  a: {
    b: [{ c: 'd' }],
    e: undefined,
  },
}

get(data, ['a', 'b', 0, 'c']) // "d"
get(data, ['not-found' as any], 'defaultValue') // "defaultValue"
get(data, ['a', 'e'], 'defaultValue') // undefined
get(data, ['a', 'e']) || 'fallback' // "fallback"

Also works on functions. If you need to override the input type, you can use get<T> in TypeScript.

About

Type-safe get function returns a nested value from an object.

License:MIT License


Languages

Language:TypeScript 100.0%