Strongly-typed function to get a nested & potentially null/undefined property value.
Install
npm install typed-get-prop --save
Usage
; ; ; // number | undefined; // string | undefined
Why do I need this?
-
Because getting a nested property value can be error-prone when parent properties can be
null
orundefined
.;// Next line will error because `cast` is optional and undefined;// Using getProp will simply return undefined rather than erroring; -
Unlike most (if not all?) other property getter libraries on NPM,
typed-get-prop
will complain at design/compile-time if you try to access a property of a typed object that doesn't exist in the model.;// Next line will error at design/compile-time because `actors` isn't a property on the Movie type. It should be `cast`.; -
Again, unlike other property getter libraries,
typed-get-prop
will correctly infer types of properties.;; // year is number | undefined at design-time
Comparison with other npm libraries
Library | Typesafe | Supports older browsers | Doesn't mutates Object.prototype | Doesn't swallow exceptions indiscriminately |
---|---|---|---|---|
get-typed-prop | ✅ | ✅ | ✅ | ✅ |
nevernull | ❌ | ❌ | ✅ | ✅ |
telvis | ✅ | ❌ | ❌ | ✅ |
ts-optchain | ✅ | ❌ Only via a custom compiler & transform | ✅ | ✅ |
@smartlyio/safe-navigation | ✅ | ❌ | ✅ | ✅ |
safe-ts | ✅ | ✅ | ✅ | ❌ |
lonely-operation | ✅ | ❌ | ✅ | ✅ |
Contributing
Got an issue or a feature request? Log it.
Pull-requests are also welcome.