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

0.1.2 • Public • Published

ts-object-path

Generate strongly-typed deep property path in typescript. Access deep property by a path.

npm version

Install

npm install ts-object-path --save

Usage

Get property path

import { createProxy, getPath } from 'ts-object-path'
 
interface IExample {
  one: number;
  two: string;
  nested: IExample;
  collection: IExample[];
}
 
const p = createProxy<IExample>();
 
getPath(p.one); // returns ['one']
getPath(p.nested.one); // returns ['nested', 'one']
getPath(p.collection[5].nested.two); // returns ['collection', 5, 'nested', 'two']
getPath(p.three); // compilation error (no such property)
 

Get deep property value

import { get } from 'ts-object-path'
 
interface IExample {
  one?: number;
  two?: string;
  nested?: IExample;
  collection?: IExample[];
}
 
const o: IExample = {
  one: 777;
  collection[
    null,
    { two: 'Hello' }
  ]
};
 
get(o, p=> p.one); // returns 777
get(o, p=> p.nested.one); // returns undefined
get(o, p=> p.collection[1].two); // returns 'Hello'
get(o, p=> p.collection[0].two, 'default'); // returns 'default'
get(o, p=> p.collection[0].one, 'default'); // compilation error (property and default value types don't match)
get(o, p=> p.three); // compilation error (no such property)
const val: number = get(o, p=> p.collection[1].two); // compilation error (string is not assignable to number)
 

Set deep property value

import { set } from 'ts-object-path'
 
interface IExample {
  one?: number;
  two?: string;
  nested?: IExample;
  collection?: IExample[];
}
 
const o: IExample = {
  one: 1;
};
 
set(o, p=> p.one, 777); // o === { one: 777 }
set(o, p=> p.nested.one, 3); // o === { one: 777, nested: { one: 3 } }
set(o, p=> p.collection[1].two, 'hello'); // o === { one: 777, nested: { one: 3 }, collection: [undefined, { two: 'hello'}] }
 

Readme

Keywords

none

Package Sidebar

Install

npm i ts-object-path

Weekly Downloads

12,276

Version

0.1.2

License

MIT

Unpacked Size

16.7 kB

Total Files

9

Last publish

Collaborators

  • taras-tymchiy