Package Exports
- ts-get-set
Readme
TS Get Set
100% Type safe get and set functions.
Installation
# npm
npm i ts-get-set
# yarn
yarn add ts-get-setUsage
import { get, set } from "ts-get-set";
const a = {
b: 5,
c: [1, 2, { d: "asdf" }],
};
let d: string = get(a, "c.2.d");
console.log(d); // "asdf"
const updatedA = set(a, "c.2.d", "fdsa");
console.log(updatedA);
// {
// b: 5,
// c: [1, 2, { d: "fdsa" }],
// };
d = get(a, "c.2.d");
console.log(d); // "fdsa"
console.log(a.c[2].d); // "fdsa"Recommended configurations
When using this library it's recommended to turn on these options in your tsconfig.json:
{
"compilerOptions": {
/* ... */
"strict": true,
"noUncheckIndexAccess": true
}
}API
get
Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.
Usage:
const obj = { a: [1, 2, { b: 3 }] };
get(obj, "a.2.b"); // 3Type:
function get<Obj extends AnyObject, Key extends string, Default = undefined>(
object: Obj,
stringPath: Key,
defaultValue?: Default
): Get<Obj, PathString<Key>, Default>;set
Usage:
const obj = {};
set(obj, "a.2.b", "hello"); // { a: [undefined, undefined, { b: "hello" }] }Type:
function set<Obj extends AnyObject, Key extends string, Value>(
object: Obj,
stringPath: Key,
value: Value
): Set<Obj, PathString<Key>, Value>;stringToPath
Converts a dot notation string to a path array
Usage:
const path = stringToPath("a.b.2.c.5");
console.log(path); // ["a", "b", "2", "c", "5"]PathString
A type that converts string to a path.
Usage:
type Path = PathString<"a.b.c.1">; // ["a", "b", "c", "1"]Get
A type that gets a property from object at specified path.
Usage:
type NestedProps = Get<{ a: { b: [1, "c"] } }, ["a", "b", "2"]>; // "c";
// or
type NestedProps = Get<{ a: { b: [1, "c"] } }, PathString<"a.b.2">>; // "c";Set
A type that sets the property to a provided value at path.
type Data = { b: number; c: string };
type NewData = Set<Data, ["c", "d"], string[]>; // { c: { d: string[]; } b: number; }
// or
type NewData = Set<Data, PathString<"c.d">, string[]>; // { c: { d: string[]; } b: number; }Roadmap
Here is the list of features that I want to add in the near future. It's not the strict set of tasks but more of a plan for the development of this package. If you have any suggestions, feel free to open an issue.
- get, set and stringToPath 100% type safety (open an issue if you've found some bug).
- Support for
[]syntax for index access. - Suggestions in dot notation string (may increase compilation time).