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

1.0.3 • Public • Published

object-path-expressions

Adds type safety to functions that accept deep path arrays

For example, given:

function pathArraysFunction(object: any, path: PropertyKey[]): any
{
    let result: any = object;
 
    for (let i = 0; i < path.length; i++)
    {
        result = result[path[i]];
    }
 
    return result;
}
 
interface ExampleNestedInterface
{
    nestedProperty1: string;
    nestedProperty2: number;
}
 
interface ExampleInterface
{
    property1: ExampleNestedInterface;
}
 
let exampleObject: ExampleInterface = {
    property1: {
        nestedProperty1: "example",
        nestedProperty2: 1234
    }
};

instead of this:

let valueWithAnyType = pathArraysFunction(exampleObject, ["property1", "nestedProperty1"]);
pathArraysFunction(exampleObject, ["invalidProperty1", "nestedProperty1"]); // ouch! runtime error

we can do this:

import { getObjectPath, PathExpression } from "object-path-expression";
 
function pathArraysFunctionWrapper<T, TLeaf>(object: T, pathExpression: PathExpression<T, TLeaf>): TLeaf
{
    let path = getObjectPath(pathExpression);
    return pathArraysFunction(object, path.path);
}
 
let valueWithTypeOfNestedProperty1 = pathArraysFunctionWrapper(exampleObject, o => o.property1.nestedProperty1);
pathArraysFunctionWrapper(exampleObject, o => o.invalidProperty1.nestedProperty1); // compile time error

Readme

Keywords

Package Sidebar

Install

npm i object-path-expression

Weekly Downloads

0

Version

1.0.3

License

MIT

Last publish

Collaborators

  • matgr1