Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
@sindresorhus/is
Advanced tools
The @sindresorhus/is npm package is a type-checking library that provides a variety of functions to assert the type of a given value. It can be used to check primitive types, built-in objects, and to perform environment checks.
Primitive type checking
Check if a value is a string.
const is = require('@sindresorhus/is');
console.log(is.string('Hello World')); // true
Built-in object checking
Check if a value is a Promise.
const is = require('@sindresorhus/is');
console.log(is.promise(new Promise(resolve => resolve()))); // true
Environment checking
Check if the current environment is Node.js.
const is = require('@sindresorhus/is');
console.log(is.nodejs); // true or false depending on the environment
Array checking
Check if a value is an Array.
const is = require('@sindresorhus/is');
console.log(is.array([1, 2, 3])); // true
Object checking
Check if a value is an Object.
const is = require('@sindresorhus/is');
console.log(is.object({foo: 'bar'})); // true
Type-check offers a more granular and customizable approach to type checking, allowing users to define custom type expressions and check values against them. It is more flexible but also more complex than @sindresorhus/is.
Check-types is a library that provides a set of predicates for type checking. It is similar to @sindresorhus/is but offers a slightly different API and additional functions for assertions and throwing errors.
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
When using is
together with TypeScript, type guards are being used to infer the correct type inside if-else statements.
import is from '@sindresorhus/is';
const padLeft = (value: string, padding: string | number) => {
if (is.number(padding)) {
// `padding` is typed as `number`
return Array(padding + 1).join(' ') + value;
}
if (is.string(padding)) {
// `padding` is typed as `string`
return padding + value;
}
throw new TypeError(`Expected 'padding' to be of type 'string' or 'number', got '${is(padding)}'.`);
}
padLeft('🦄', 3);
//=> ' 🦄'
padLeft('🦄', '🌈');
//=> '🌈🦄'
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 an error 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.
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.
Returns true
for any object that implements its own .next()
and .throw()
methods and has a function definition for Symbol.iterator
.
Returns true
for any async
function that can be called with the await
operator.
is.asyncFunction(async () => {});
// => true
is.asyncFunction(() => {});
// => false
Returns true
for any bound
function.
is.boundFunction(() => {});
// => true
is.boundFunction(function () {}.bind(null));
// => true
is.boundFunction(function () {});
// => false
Returns true
if the value is a string
and the .length
is 0.
Returns true
if the value is a string
and the .length
is more than 0.
Returns true
if is.emptyString(value)
or if it's a string
that is all whitespace.
Returns true
if the value is an Array
and the .length
is 0.
Returns true
if the value is an Array
and the .length
is more than 0.
Returns true
if the value is an Object
and Object.keys(value).length
is 0.
Please note that Object.keys
returns only own enumerable properties. Hence something like this can happen:
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: true,
enumerable: false,
configurable: true
});
is.emptyObject(object1);
// => true
Returns true
if the value is an Object
and Object.keys(value).length
is more than 0.
Returns true
if the value is a Set
and the .size
is 0.
Returns true
if the value is a Set
and the .size
is more than 0.
Returns true
if the value is a Map
and the .size
is 0.
Returns true
if the value is a Map
and the .size
is more than 0.
Returns true
if value
is a direct instance of class
.
is.directInstanceOf(new Error(), Error);
//=> true
class UnicornError extends Error {};
is.directInstanceOf(new UnicornError(), Error);
//=> false
Returns true
if value
is an instance of the URL
class.
const url = new URL('https://example.com');
is.urlInstance(url);
//=> true
Returns true
for all values that evaluate to true in a boolean context:
is.truthy('🦄');
//=> true
is.truthy(undefined);
//=> false
Returns true
if value
is one of: false
, 0
, ''
, null
, undefined
, NaN
.
JavaScript primitives are as follows: null
, undefined
, string
, number
, boolean
, symbol
.
Returns true
if value
is a safe integer.
An object is plain if it's created by either {}
, new Object()
, or Object.create(null)
.
Returns true
for instances created by a ES2015 class.
A value
is array-like if it is not a function and has a value.length
that is a safe integer greater than or equal to 0.
is.arrayLike(document.forms);
//=> true
function () {
is.arrayLike(arguments);
//=> true
}
Check if value
(number) is in the given range
. The range is an array of two values, lower bound and upper bound, in no specific order.
is.inRange(3, [0, 5]);
is.inRange(3, [5, 0]);
is.inRange(0, [-2, 2]);
Check if value
(number) is in the range of 0
to upperBound
.
is.inRange(3, 10);
Returns true
if value
is a DOM Element.
Returns true
if value
is a Node.js stream.
const fs = require('fs');
is.nodeStream(fs.createReadStream('unicorn.png'));
//=> true
Returns true
if value
is an Observable
.
const {Observable} = require('rxjs');
is.observable(new Observable());
//=> true
Check if value
is Infinity
or -Infinity
.
Returns true
if value
is an even integer.
Returns true
if value
is an odd integer.
Returns true
if any of the input values
returns true in the predicate
:
is.any(is.string, {}, true, '🦄');
//=> true
is.any(is.boolean, 'unicorns', [], new Map());
//=> false
Returns true
if all of the input values
returns true in the predicate
:
is.all(is.object, {}, new Map(), new Set());
//=> true
is.all(is.string, '🦄', [], 'unicorns');
//=> false
There are hundreds of type checking modules on npm, unfortunately, I couldn't find any that fit my needs:
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.
MIT
FAQs
Type check values
The npm package @sindresorhus/is receives a total of 17,787,113 weekly downloads. As such, @sindresorhus/is popularity was classified as popular.
We found that @sindresorhus/is demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.