Skip to content

Type safe object field string paths for typescript.

License

Notifications You must be signed in to change notification settings

nick-lvov-dev/typed-path

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Typed Path


Problem

Types are lost when string paths are used in typescript.
I.e. _.get, _.map, _.set, R.pluck from libraries like lodash, ramda.
It makes those methods dangerous in case of refactoring, the same as JavaScript.


Solution

Errors

With typed-path typescript can check paths and warns you about errors.

.$path

@m-abboud
Also you can get access to the path string using $path special field.

Like this:

    console.log(tp<TestType>().a.b.c.d.$path); // this will output "a.b.c.d"

.$raw

@dcbrwn
If you need a raw path, which is of type string[] - you can get it using $raw special field.

    console.log(tp<TestType>().a.b.c.d.$raw); // this will output ["a", "b", "c", "d"]

Additional handlers

@nick-lvov-dev

You can extend path handlers functionality using additional handlers:

const testAdditionalHandlers = {
    $url: (path: string[]) => path.join('/')
}

console.log(tp<TestType, typeof testAdditionalHandlers>(testAdditionalHandlers).a.b.c.$url); // this will output "a/b/c"

The additional handlers are also chainable:

const testAdditionalHandlers = {
    $abs: (path: string[]) => typedPath<TestType, typeof testAdditionalHandlers>(testAdditionalHandlers, ['', ...path]),
    $url: (path: string[]) => path.join('/')
}

console.log(tp<TestType, typeof testAdditionalHandlers>(testAdditionalHandlers).a.b.c.$abs.$url); // this will output "/a/b/c"

Suggestions

Also typed-path allows typescript to suggest field names for you.

License

Copyright (c) 2017 Oleksandr Beshchuk <[email protected]>
Licensed under the Apache License.

About

Type safe object field string paths for typescript.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 100.0%