Gathering detailed insights and metrics for @marionebl/is
Gathering detailed insights and metrics for @marionebl/is
Gathering detailed insights and metrics for @marionebl/is
Gathering detailed insights and metrics for @marionebl/is
npm install @marionebl/is
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,684 Stars
233 Commits
112 Forks
19 Watching
1 Branches
50 Contributors
Updated on 24 Nov 2024
TypeScript (100%)
Cumulative downloads
Total Downloads
Last day
55.6%
2,397
Compared to previous day
Last week
97.8%
7,703
Compared to previous week
Last month
724.1%
17,800
Compared to previous month
Last year
-11.6%
50,082
Compared to previous year
8
Type check values
For example, is.string('🦄') //=> true
1npm install @sindresorhus/is
1import is from '@sindresorhus/is'; 2 3is('🦄'); 4//=> 'string' 5 6is(new Map()); 7//=> 'Map' 8 9is.number(6); 10//=> true
Assertions perform the same type checks, but throw an error if the type does not match.
1import {assert} from '@sindresorhus/is'; 2 3assert.string(2); 4//=> Error: Expected value which is `string`, received value of type `number`.
Assertions (except assertAll
and assertAny
) also support an optional custom error message.
1import {assert} from '@sindresorhus/is';
2
3assert.nonEmptyString(process.env.API_URL, 'The API_URL environment variable is required.');
4//=> Error: The API_URL environment variable is required.
And with TypeScript:
1import {assert} from '@sindresorhus/is'; 2 3assert.string(foo); 4// `foo` is now typed as a `string`.
Named exports allow tooling to perform tree-shaking, potentially reducing bundle size by including only code from the methods that are used.
Every method listed below is available as a named export. Each method is prefixed by either is
or assert
depending on usage.
For example:
1import {assertNull, isUndefined} from '@sindresorhus/is';
Returns the type of value
.
Primitives are lowercase and object types are camelcase.
Example:
'undefined'
'null'
'string'
'symbol'
'Array'
'Function'
'Object'
This method is also exported as detect
. You can import it like this:
1import {detect} from '@sindresorhus/is';
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 return a boolean for whether the value is of the desired type.
Note: is.number(NaN)
returns false
. This intentionally deviates from typeof
behavior to increase user-friendliness of is
type checks.
Returns true if value
is an array and all of its items match the assertion (if provided).
1is.array(value); // Validate `value` is an array. 2is.array(value, is.number); // Validate `value` is an array and all of its items are numbers.
Keep in mind that functions are objects too.
Returns true
for a string that represents a number satisfying is.number
, for example, '42'
and '-8.3'
.
Note: 'NaN'
returns false
, but 'Infinity'
and '-Infinity'
return true
.
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.
1is.asyncFunction(async () => {}); 2//=> true 3 4is.asyncFunction(() => {}); 5//=> false
1is.asyncGenerator( 2 (async function * () { 3 yield 4; 4 })() 5); 6//=> true 7 8is.asyncGenerator( 9 (function * () { 10 yield 4; 11 })() 12); 13//=> false
1is.asyncGeneratorFunction(async function * () { 2 yield 4; 3}); 4//=> true 5 6is.asyncGeneratorFunction(function * () { 7 yield 4; 8}); 9//=> false
Returns true
for any bound
function.
1is.boundFunction(() => {}); 2//=> true 3 4is.boundFunction(function () {}.bind(null)); 5//=> true 6 7is.boundFunction(function () {}); 8//=> false
TypeScript-only. Returns true
if value
is a member of enum
.
1enum Direction { 2 Ascending = 'ascending', 3 Descending = 'descending' 4} 5 6is.enumCase('ascending', Direction); 7//=> true 8 9is.enumCase('other', Direction); 10//=> false
Returns true
if the value is a string
and the .length
is 0.
Returns true
if is.emptyString(value)
or if it's a string
that is all whitespace.
Returns true
if the value is a string
and the .length
is more than 0.
Returns true
if the value is a string
that is not empty and not whitespace.
1const values = ['property1', '', null, 'property2', ' ', undefined]; 2 3values.filter(is.nonEmptyStringAndNotWhitespace); 4//=> ['property1', 'property2']
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:
1const object1 = {};
2
3Object.defineProperty(object1, 'property1', {
4 value: 42,
5 writable: true,
6 enumerable: false,
7 configurable: true
8});
9
10is.emptyObject(object1);
11//=> 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
.
1is.directInstanceOf(new Error(), Error); 2//=> true 3 4class UnicornError extends Error {} 5 6is.directInstanceOf(new UnicornError(), Error); 7//=> false
Returns true
if value
is an instance of the URL
class.
1const url = new URL('https://example.com');
2
3is.urlInstance(url);
4//=> true
Returns true
if value
is a URL string.
Note: this only does basic checking using the URL
class constructor.
1const url = 'https://example.com'; 2 3is.urlString(url); 4//=> true 5 6is.urlString(new URL(url)); 7//=> false
Returns true
for all values that evaluate to true in a boolean context:
1is.truthy('🦄'); 2//=> true 3 4is.truthy(undefined); 5//=> false
Returns true
if value
is one of: false
, 0
, ''
, null
, undefined
, NaN
.
JavaScript primitives are as follows:
null
undefined
string
number
boolean
symbol
bigint
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
if the value is a class constructor.
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.
1is.arrayLike(document.forms);
2//=> true
3
4function foo() {
5 is.arrayLike(arguments);
6 //=> true
7}
8foo();
A value
is tuple-like if it matches the provided guards
array both in .length
and in types.
1is.tupleLike([1], [is.number]); 2//=> true
1function foo() { 2 const tuple = [1, '2', true]; 3 if (is.tupleLike(tuple, [is.number, is.string, is.boolean])) { 4 tuple // [number, string, boolean] 5 } 6} 7 8foo();
Check if value
is a number and is more than 0.
Check if value
is a number and is less than 0.
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.
1is.inRange(3, [0, 5]); 2is.inRange(3, [5, 0]); 3is.inRange(0, [-2, 2]);
Check if value
(number) is in the range of 0
to upperBound
.
1is.inRange(3, 10);
Returns true
if value
is an HTMLElement.
Returns true
if value
is a Node.js stream.
1import fs from 'node:fs'; 2 3is.nodeStream(fs.createReadStream('unicorn.png')); 4//=> true
Returns true
if value
is an Observable
.
1import {Observable} from 'rxjs'; 2 3is.observable(new Observable()); 4//=> 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 value
can be used as an object property key (either string
, number
, or symbol
).
Returns true
if value
is an instance of the FormData
class.
1const data = new FormData(); 2 3is.formData(data); 4//=> true
Returns true
if value
is an instance of the URLSearchParams
class.
1const searchParams = new URLSearchParams();
2
3is.urlSearchParams(searchParams);
4//=> true
Using a single predicate
argument, returns true
if any of the input values
returns true in the predicate
:
1is.any(is.string, {}, true, '🦄'); 2//=> true 3 4is.any(is.boolean, 'unicorns', [], new Map()); 5//=> false
Using an array of predicate[]
, returns true
if any of the input values
returns true for any of the predicates
provided in an array:
1is.any([is.string, is.number], {}, true, '🦄'); 2//=> true 3 4is.any([is.boolean, is.number], 'unicorns', [], new Map()); 5//=> false
Returns true
if all of the input values
returns true in the predicate
:
1is.all(is.object, {}, new Map(), new Set()); 2//=> true 3 4is.all(is.string, '🦄', [], 'unicorns'); 5//=> false
Returns true
if the value is a valid date.
All Date
objects have an internal timestamp value which is the number of milliseconds since the Unix epoch. When a new Date
is constructed with bad inputs, no error is thrown. Instead, a new Date
object is returned. But the internal timestamp value is set to NaN
, which is an 'Invalid Date'
. Bad inputs can be an non-parsable date string, a non-numeric value or a number that is outside of the expected range for a date value.
1const valid = new Date('2000-01-01');
2
3is.date(valid);
4//=> true
5valid.getTime();
6//=> 946684800000
7valid.toUTCString();
8//=> 'Sat, 01 Jan 2000 00:00:00 GMT'
9is.validDate(valid);
10//=> true
11
12const invalid = new Date('Not a parsable date string');
13
14is.date(invalid);
15//=> true
16invalid.getTime();
17//=> NaN
18invalid.toUTCString();
19//=> 'Invalid Date'
20is.validDate(invalid);
21//=> false
Returns true
if the value is a safe integer that is greater than or equal to zero.
This can be useful to confirm that a value is a valid count of something, ie. 0 or more.
Returns true
if the value is a string with only whitespace characters.
When using is
together with TypeScript, type guards are being used extensively to infer the correct type inside if-else statements.
1import is from '@sindresorhus/is'; 2 3const padLeft = (value: string, padding: string | number) => { 4 if (is.number(padding)) { 5 // `padding` is typed as `number` 6 return Array(padding + 1).join(' ') + value; 7 } 8 9 if (is.string(padding)) { 10 // `padding` is typed as `string` 11 return padding + value; 12 } 13 14 throw new TypeError(`Expected 'padding' to be of type 'string' or 'number', got '${is(padding)}'.`); 15} 16 17padLeft('🦄', 3); 18//=> ' 🦄' 19 20padLeft('🦄', '🌈'); 21//=> '🌈🦄'
The type guards are also available as type assertions, which throw an error for unexpected types. It is a convenient one-line version of the often repetitive "if-not-expected-type-throw" pattern.
1import {assert} from '@sindresorhus/is'; 2 3const handleMovieRatingApiResponse = (response: unknown) => { 4 assert.plainObject(response); 5 // `response` is now typed as a plain `object` with `unknown` properties. 6 7 assert.number(response.rating); 8 // `response.rating` is now typed as a `number`. 9 10 assert.string(response.title); 11 // `response.title` is now typed as a `string`. 12 13 return `${response.title} (${response.rating * 10})`; 14}; 15 16handleMovieRatingApiResponse({rating: 0.87, title: 'The Matrix'}); 17//=> 'The Matrix (8.7)' 18 19// This throws an error. 20handleMovieRatingApiResponse({rating: '🦄'});
The type guards and type assertions are aware of generic type parameters, such as Promise<T>
and Map<Key, Value>
. The default is unknown
for most cases, since is
cannot check them at runtime. If the generic type is known at compile-time, either implicitly (inferred) or explicitly (provided), is
propagates the type so it can be used later.
Use generic type parameters with caution. They are only checked by the TypeScript compiler, and not checked by is
at runtime. This can lead to unexpected behavior, where the generic type is assumed at compile-time, but actually is something completely different at runtime. It is best to use unknown
(default) and type-check the value of the generic type parameter at runtime with is
or assert
.
1import {assert} from '@sindresorhus/is'; 2 3async function badNumberAssumption(input: unknown) { 4 // Bad assumption about the generic type parameter fools the compile-time type system. 5 assert.promise<number>(input); 6 // `input` is a `Promise` but only assumed to be `Promise<number>`. 7 8 const resolved = await input; 9 // `resolved` is typed as `number` but was not actually checked at runtime. 10 11 // Multiplication will return NaN if the input promise did not actually contain a number. 12 return 2 * resolved; 13} 14 15async function goodNumberAssertion(input: unknown) { 16 assert.promise(input); 17 // `input` is typed as `Promise<unknown>` 18 19 const resolved = await input; 20 // `resolved` is typed as `unknown` 21 22 assert.number(resolved); 23 // `resolved` is typed as `number` 24 25 // Uses runtime checks so only numbers will reach the multiplication. 26 return 2 * resolved; 27} 28 29badNumberAssumption(Promise.resolve('An unexpected string')); 30//=> NaN 31 32// This correctly throws an error because of the unexpected string value. 33goodNumberAssertion(Promise.resolve('An unexpected string'));
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.
instanceof
instead of this package?instanceof
does not work correctly for all types and it does not work across realms. Examples of realms are iframes, windows, web workers, and the vm
module in Node.js.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
security policy file detected
Details
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
Found 16/30 approved changesets -- score normalized to 5
Reason
2 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 2
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More