Type check values:
is.string('π¦') //=> true
$ npm install @sindresorhus/is
const is = require('@sindresorhus/is');
is('π¦');
//=> 'string'
is(new Map());
//=> 'Map'
is.number(6);
//=> true
Returns the type of value
.
Primitives are lowercase and object types are camelcase.
Example:
'undefined'
'null'
'string'
'symbol'
'Array'
'Function'
'Object'
Note: It will throw if you try to feed it object-wrapped primitives, as that's a bad practice. For example new String('foo')
.
All the below methods accept a value and returns a boolean for whether the value is of the desired type.
Returns true
for instances created by a ES2015 class.
Keep in mind that functions are objects too.
Returns true
for any object with a .then()
and .catch()
method. Prefer this one over .nativePromise()
as you usually want to allow userland promise implementations too.
JavaScript primitives are as follows: null
, undefined
, string
, number
, boolean
, symbol
.
An object is plain if it's created by either {}
, new Object()
, or Object.create(null)
.
There are hundreds of type checking modules on npm, unfortunately, I couldn't find any that fit my needs:
- Includes both type methods and ability to get the type
- Types of primitives returned as lowercase and object types as camelcase
- Covers all built-ins
- Unsurprising behavior
- Well-maintained
- Comprehensive test suite
For the ones I found, pick 3 of these.
The most common mistakes I noticed in these modules was using instanceof
for type checking, forgetting that functions are objects, and omitting symbol
as a primitive.
- is-stream - Check if something is a Node.js stream
- is-observable - Check if a value is an Observable
- file-type - Detect the file type of a Buffer/Uint8Array
- is-ip - Check if a string is an IP address
- is-array-sorted - Check if an Array is sorted
- is-error-constructor - Check if a value is an error constructor
- is-empty-iterable - Check if an Iterable is empty
MIT Β© Sindre Sorhus