Dynamic type checking
Static type checking does not work in all situations, especially when dealing with data from unknown or untrusted sources. In those cases the application must resort to dynamic type checking at run-time.
Check data types at runtime
For example:
;
or
;
You can use these types:
- 'global' - global object
- 'process' - NodeJS process
- null - null value
- 'null' - null value
- Boolean - primitive booleans and instances of Boolean
- 'boolean' - primitive booleans only
- 'Boolean' - instances of Boolean only
- String - primitive strings and instances of String
- 'string' - primitive strings only
- 'String' - instances of String only
- 'String Iterator' - String iterator
- Number - instances of Number only
- 'number' - primitive numbers only
- 'Number' - instances of Number only
- Symbol - symbols (they are primitives)
- Object - any objects which toString tag is Object
- Function - any function (AsyncFunction and GeneratorFunction)
- 'AsyncFunction' - async functions
- 'GeneratorFunction' - generator functions
- JSON - any valid json string
- Array - any objects which toString tag is Array
- 'Array Iterator' - array iterator (for example, [].keys())
- RegExp
- Date
- Promise
- Map
- 'Map Iterator'
- WeakMap
- Set
- 'Set Iterator'
- WeakSet
- Error
- DataView
- Float32Array
- Uint8Array
- ...
- Classes and constructors
- [Symbol.toStringTag]
- toString tag
Do not use 'undefined' type, use 'optional' or 'opt' key.
Use destructuring assignment to unpack properties from objects into distinct variables.
The function returns an object with all the variables.
Installation
npm i type-of-data
Usage
const typeOf = ; { // Throw a TypeError if type is not correct ; /* Here you can be sure that the types a correct... */}
More examples:
// Single definition; // Array of definitions;
Tests:
;
Throws TypeError:
;
Tip
You can find more examples in tests.