Share a strong typed object path package!
Xusheng Yang
Posted on May 29, 2023
I've used some packages related to object path before, but I found that the type support of these packages is not particularly comprehensive, such as lodash, react-hook-form, formik, mongodb client, etc.
There are more or less several problems with these packages:
- There is no type constraint, so code autocompletion cannot be provided;
- The generated path is not standardized. Most of them only support 'a.b.c'. This kind of path has some shortcomings, is not unified with other packages (such as yup), cannot distinguish between object/array, and most of them treat numbers as arrays, but they may actually be object with number keys;
- The corresponding type cannot be inferred from the path.
Because I had a high demand for object path when writing the open-source project react-happy-form, I wrote the package object-standard-path separately:
- Provides very comprehensive type support (including handling of some special types such as any, Map, etc.);
- Generates standard paths;
- Supports inferring types through paths. It is also very easy to use, without any dependencies, and less than 1k in package size. If anyone needs it, you can try it :)
Repo address: https://github.com/react-earth/object-standard-path
If possible, you can give it a star. Every star is my motivation for continuous updates in the future. Thank you! π
import { Path, PathValue, pathGet, pathSet } from 'object-standard-path';
type Test = {
value: string;
array: {
value: string;
}[];
};
type TestPath = Path<Test>;
// result: "value" | "array" | `array[${number}]` | `array[${number}].value`
type TestPathValue = PathValue<Test, 'array[0]'>;
// result: { value: string }
const object = {
array: [
{
value: 1,
},
],
};
const result = pathGet(object, 'array[0].value');
// result: 1
pathSet(object, 'array[0].value', 2);
// result: { array: [{ value: 2 }] }
π πͺ π
π©
Xusheng Yang
Posted on May 29, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
privacy Caught in the Crunch My Journey from Snacks to 2 Million Exposed Users Privacy
November 30, 2024