typed-any-access
Safe wrapper for any
and JSON in TypeScript.
Say goodbye to TypeError: Cannot read property 'key' of undefinied
.
Install
npm i --save typed-any-access
Quick start
; // Unsafe object; // Create safe object; // Safe access .get"persons" .get0 .get"firstName" .stringOrDefault"no name"; // value === "John"
Guide
This libary makes access to objects of type any
type-safe by providing default values and a typed interface.
Getting started
Create a Any
object by either wrapping an any
or parsing a JSON literal.
If the parsing fails, new Any(null)
will be returned.
Any.parseJSON()
does not throw.
// Unsafe object, which may be the result of JSON.parse().;// Safe wrap;
// Parse JSON literal and wrap safely;
Referencing sub objects
getkey: string | number: Any
;;
Instead of accesing sub objects using the unsafe subscript access (object['key']
), the get()
operator is used.
If the root object is an array, use get(2)
to access the 3rd value.
If the root object is a dictionary, use get("key")
to access the value that is defined at the key key
.
If the sub object cannot be accessed, because it does not exist or the root object's type is incompatible,
new Any(null)
is returned.
; ; .get"myArray" .get1 .get"name" .stringValue; // nameOfObject2 === "object2"
Reading a value
- Returns
null
if value is not present or the conversion failed.
stringOrNull: string | nullnumberOrNull: number | nullbooleanOrNull: boolean | nulldictionaryOrNull: | nullarrayOrNull: Any | null
Reading a value with given fallback
- Returns the given default value if value is not present or the conversion failed.
stringOrDefaultvalue: string: stringnumberOrDefaultvalue: number: numberbooleanOrDefaultvalue: boolean: boolean
Reading a value with conventional fallback
- Either returns the value or a conventional default value.
stringValue: stringnumberValue: numberbooleanValue: booleandictionaryValue: arrayValue: Any
Function | Fallback Value |
---|---|
stringValue() |
"" |
numberValue() |
0 |
booleanValue() |
false |
dictionaryValue() |
{} |
arrayValue() |
[] |
Getting the object's type
The type
property can be used to determin the object's type.
This is useful for custom parsing of tree structures or fallback mechanics.
Possible types are:
string
number
boolean
dictionary
array
null
; ; if wrappedDict.type === Type.dictionary else
Parsing embedded JSON string literals
If an object embeds a JSON string literal, use the parsed()
operator to try parsing it into an object.
If the object is a string, this operator treats the value as a JSON string and tries to parse it into an object and returns it.
If the object is no string or the parsing failed, the current object will be returned without change. This replaces the unhandy manual approach of breaking the operator chain.
;; // Instead ofAny.parsedJSONsafeObject.get"jsonString".stringValue.get"hello".stringValue; // Do thissafeObject.get"jsonString".parsed.get"hello".stringValue;