Highly recommended to always declare the object, path, and default with as const or explicitly type,
this will prevent any short circuiting or narrowing logic done by TypeScript intepreter.
// ❌ This will work and type correctly sometimes, but will fail on larger and more complex objects, see belownav({foo: 'bar'},['foo'])//=> string// ❌ If path is not asserted with `as const` it can fail on arrays since it short circuits to the path to (string | number)[]constpath=['foo',0,'bar']nav({foo: [{bar: true}]},['foo',0,'bar'])// => { bar: boolean; }[] | { bar: boolean; }nav({foo: [{bar: true}]},path)// <= Path! Argument of type '(string | number)[]' is not assignable to parameter of type...// ✔️ Always assert the object and path.constpath=['foo',0,'bar']asconstnav({foo: [{bar: true}]}asconst,path)//=> truenav({foo: [{bar: 'foobar'}]}asconst,path)//=> 'foobar'// ✔️ Or explicitly type the object and pathtypefoobar={foo: [{bar: true}]};typepath=['foo',0,'bar']constfoobar: foobar=awaitfoobarAPI(...)constpath: path=['foo',0,'bar']nav(foobar,path)//=> true// 🆗 Or use the built in generics (while acceptable is also extra verbose)typefoobar={foo: [{bar: true}]};nav<foobar,['foo',0,'bar']>(foobar,['foo',0,'bar'])//=> true// 🆗 It is OK to not assert the object, but it will be less narrow than possiblenav({foo: 'bar'},['foo']asconst)//=> string
Idiosyncrasies
Q: Why do we have to as const?
A: Read more on const assertion in this TS 3.4 Release or in this StackOverflow answer. In short, the TS intepreter uses this to narrow types down from type string to something narrower such as foobar. It also automatically narrows objects/tuples. Since the path parameter is a tuple, we can't afford narrowing this type, otherwise it will blow up the inference engine.
codyduong/nav
Nav
A navigation utility for parsing API responses.
Written in TypeScript with strong inference engine. Handles all your data for you.
Install
npm install @codyduong/nav
yarn add @codyduong/nav
Usage
Patterns
API Response
Anti-Patterns
Highly recommended to always declare the object, path, and default with
as const
or explicitly type, this will prevent any short circuiting or narrowing logic done by TypeScript intepreter.Idiosyncrasies
Q: Why do we have to
as const
?A: Read more on const assertion in this TS 3.4 Release or in this StackOverflow answer. In short, the TS intepreter uses this to narrow types down from type
string
to something narrower such asfoobar
. It also automatically narrows objects/tuples. Since the path parameter is a tuple, we can't afford narrowing this type, otherwise it will blow up the inference engine.Contributing
Any contributing is welcome.