is-defined-type
Checks if a variable in a nested object is defined and optionally also check it's type.
This is especially useful for validating API responses which contain many nested objects. For example, if you expect a response like this:
var res = first: second: third: "target"
You could get "target" by using:
var val = resfirstsecondthird;
But if first, second or third is undefined or not an object you get an exception. So you can do some verbose checks:
var val = res && resfirst && resfirstsecond && typeof resfirstsecondthird !== 'undefined' ? resfirstsecondthird : null;
Or just use isDefinedType:
var val = ? resfirstsecondthird : null;
You can even make sure it is a string:
var val = ? resfirstsecondthird : null;
Pass along 'value' with the types to check and the value of the checked variable will be returned if it is defined and matches a given type
var val = || null; // val === 'target'
Or specify a default value to be returned if the value is not defined
var val = ; // val === 'target'var val2 = ; // val2 === 'Default'
Usage
;
- input: Object to check
- path: Optional path to key in input to check. Can be a string of keys with a dot between each level inside the object 'res.user.name' or an array of strings: ['res','user','name']. If any of the keys before the last one does not point to an object the function will return false.
- type: Optional type which the last key in the path must match if it is not undefined. This must provided as single lowercase string or an array of lowercase strings if multiple types are valid. Possible values are: string | object | array | number | null. Null and array are treated as a special cases and will not match object. If 'value' is in type the function result will contain the checked variable if it is defined and matches a given type.
- defaultValue: Optional default value which will be returned if path is not defined or does not match type. When defaultValue is not undefined will return value when path is defined and matches type
Installation
Browser
Node.js
npm install is-defined-type --save
const isDefinedType = ;
Examples
var data = user: name: 'Alice' email: null credentials: username: 'alice123' password: 'secret' age: 10 aliases: 'foo' 'bar' // Not nested; // true; // false // Not nested with type check; // true; // false // Nested; // true; // false // Deeply nested; // true; // true; // true; // true; // false; // false // Deeply nested with type check; // true; // true; // true; // false; // false // Return default value; // Alice; // Bob