@philiprehberger/dotpath-ts
v0.1.2
Published
Type-safe dot-notation access and mutation for nested objects
Readme
@philiprehberger/dotpath-ts
Type-safe dot-notation access and mutation for nested objects
Installation
npm install @philiprehberger/dotpath-tsUsage
get
import { get } from '@philiprehberger/dotpath-ts';
const obj = { a: { b: { c: 42 } } };
get(obj, 'a.b.c'); // 42
get(obj, 'a.b.missing'); // undefined
get(obj, 'a.b.missing', 0); // 0 (default value)set
import { set } from '@philiprehberger/dotpath-ts';
const obj = { a: { b: { c: 42 } } };
const updated = set(obj, 'a.b.c', 100);
// updated.a.b.c === 100
// obj.a.b.c === 42 (original unchanged)has
import { has } from '@philiprehberger/dotpath-ts';
const obj = { a: { b: { c: 42 } } };
has(obj, 'a.b.c'); // true
has(obj, 'a.b.missing'); // falsedel
import { del } from '@philiprehberger/dotpath-ts';
const obj = { a: { b: { c: 42, d: 'hello' } } };
const result = del(obj, 'a.b.c');
// result.a.b === { d: 'hello' }
// obj.a.b.c === 42 (original unchanged)update
import { update } from '@philiprehberger/dotpath-ts';
const obj = { a: { b: { count: 5 } } };
const result = update(obj, 'a.b.count', (v) => (v as number) * 2);
// result.a.b.count === 10
// obj.a.b.count === 5 (original unchanged)API
| Function | Signature | Description |
|----------|-----------|-------------|
| get | get(obj, path, defaultValue?) | Retrieve a value at a dot-notation path |
| set | set(obj, path, value) | Immutably set a value at a dot-notation path |
| has | has(obj, path) | Check whether a path exists in an object |
| del | del(obj, path) | Immutably remove a property at a dot-notation path |
| update | update(obj, path, fn) | Get, transform, and immutably set a value at a path |
Type Utilities
| Type | Description |
|------|-------------|
| Paths<T> | All valid dot-path strings for an object type (depth limit 5) |
| PathValue<T, P> | The type at a given dot path within an object type |
Development
npm install
npm run build
npm testSupport
If you find this project useful:
