• Stars
    star
    1,678
  • Rank 27,830 (Top 0.6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Type check values

is

Type check values

For example, is.string('🦄') //=> true

Highlights

Install

npm install @sindresorhus/is

Usage

import is from '@sindresorhus/is';

is('🦄');
//=> 'string'

is(new Map());
//=> 'Map'

is.number(6);
//=> true

Assertions perform the same type checks, but throw an error if the type does not match.

import {assert} from '@sindresorhus/is';

assert.string(2);
//=> Error: Expected value which is `string`, received value of type `number`.

And with TypeScript:

import {assert} from '@sindresorhus/is';

assert.string(foo);
// `foo` is now typed as a `string`.

API

is(value)

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').

is.{method}

All the below methods accept a value and returns a boolean for whether the value is of the desired type.

Primitives

.undefined(value)
.null(value)

Note: TypeScript users must use .null_() because of a TypeScript naming limitation.

.string(value)
.number(value)

Note: is.number(NaN) returns false. This intentionally deviates from typeof behavior to increase user-friendliness of is type checks.

.boolean(value)
.symbol(value)
.bigint(value)

Built-in types

.array(value, assertion?)

Returns true if value is an array and all of its items match the assertion (if provided).

is.array(value); // Validate `value` is an array.
is.array(value, is.number); // Validate `value` is an array and all of its items are numbers.
.function(value)

Note: TypeScript users must use .function_() because of a TypeScript naming limitation.

.buffer(value)
.blob(value)
.object(value)

Keep in mind that functions are objects too.

.numericString(value)

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.

.regExp(value)
.date(value)
.error(value)
.nativePromise(value)
.promise(value)

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.

.generator(value)

Returns true for any object that implements its own .next() and .throw() methods and has a function definition for Symbol.iterator.

.generatorFunction(value)
.asyncFunction(value)

Returns true for any async function that can be called with the await operator.

is.asyncFunction(async () => {});
//=> true

is.asyncFunction(() => {});
//=> false
.asyncGenerator(value)
is.asyncGenerator(
	(async function * () {
		yield 4;
	})()
);
//=> true

is.asyncGenerator(
	(function * () {
		yield 4;
	})()
);
//=> false
.asyncGeneratorFunction(value)
is.asyncGeneratorFunction(async function * () {
	yield 4;
});
//=> true

is.asyncGeneratorFunction(function * () {
	yield 4;
});
//=> false
.boundFunction(value)

Returns true for any bound function.

is.boundFunction(() => {});
//=> true

is.boundFunction(function () {}.bind(null));
//=> true

is.boundFunction(function () {});
//=> false
.map(value)
.set(value)
.weakMap(value)
.weakSet(value)
.weakRef(value)

Typed arrays

.int8Array(value)
.uint8Array(value)
.uint8ClampedArray(value)
.int16Array(value)
.uint16Array(value)
.int32Array(value)
.uint32Array(value)
.float32Array(value)
.float64Array(value)
.bigInt64Array(value)
.bigUint64Array(value)

Structured data

.arrayBuffer(value)
.sharedArrayBuffer(value)
.dataView(value)
.enumCase(value, enum)

TypeScript-only. Returns true if value is a member of enum.

enum Direction {
	Ascending = 'ascending',
	Descending = 'descending'
}

is.enumCase('ascending', Direction);
//=> true

is.enumCase('other', Direction);
//=> false

Emptiness

.emptyString(value)

Returns true if the value is a string and the .length is 0.

.emptyStringOrWhitespace(value)

Returns true if is.emptyString(value) or if it's a string that is all whitespace.

.nonEmptyString(value)

Returns true if the value is a string and the .length is more than 0.

.nonEmptyStringAndNotWhitespace(value)

Returns true if the value is a string that is not empty and not whitespace.

const values = ['property1', '', null, 'property2', '    ', undefined];

values.filter(is.nonEmptyStringAndNotWhitespace);
//=> ['property1', 'property2']
.emptyArray(value)

Returns true if the value is an Array and the .length is 0.

.nonEmptyArray(value)

Returns true if the value is an Array and the .length is more than 0.

.emptyObject(value)

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
.nonEmptyObject(value)

Returns true if the value is an Object and Object.keys(value).length is more than 0.

.emptySet(value)

Returns true if the value is a Set and the .size is 0.

.nonEmptySet(Value)

Returns true if the value is a Set and the .size is more than 0.

.emptyMap(value)

Returns true if the value is a Map and the .size is 0.

.nonEmptyMap(value)

Returns true if the value is a Map and the .size is more than 0.

Miscellaneous

.directInstanceOf(value, class)

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
.urlInstance(value)

Returns true if value is an instance of the URL class.

const url = new URL('https://example.com');

is.urlInstance(url);
//=> true
.urlString(value)

Returns true if value is a URL string.

Note: this only does basic checking using the URL class constructor.

const url = 'https://example.com';

is.urlString(url);
//=> true

is.urlString(new URL(url));
//=> false
.truthy(value)

Returns true for all values that evaluate to true in a boolean context:

is.truthy('🦄');
//=> true

is.truthy(undefined);
//=> false
.falsy(value)

Returns true if value is one of: false, 0, '', null, undefined, NaN.

.nan(value)
.nullOrUndefined(value)
.primitive(value)

JavaScript primitives are as follows: null, undefined, string, number, boolean, symbol.

.integer(value)
.safeInteger(value)

Returns true if value is a safe integer.

.plainObject(value)

An object is plain if it's created by either {}, new Object(), or Object.create(null).

.iterable(value)
.asyncIterable(value)
.class(value)

Returns true for instances created by a class.

Note: TypeScript users must use .class_() because of a TypeScript naming limitation.

.typedArray(value)
.arrayLike(value)

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 foo() {
	is.arrayLike(arguments);
	//=> true
}
foo();
.inRange(value, range)

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]);
.inRange(value, upperBound)

Check if value (number) is in the range of 0 to upperBound.

is.inRange(3, 10);
.domElement(value)

Returns true if value is a DOM Element.

.nodeStream(value)

Returns true if value is a Node.js stream.

import fs from 'node:fs';

is.nodeStream(fs.createReadStream('unicorn.png'));
//=> true
.observable(value)

Returns true if value is an Observable.

import {Observable} from 'rxjs';

is.observable(new Observable());
//=> true
.infinite(value)

Check if value is Infinity or -Infinity.

.evenInteger(value)

Returns true if value is an even integer.

.oddInteger(value)

Returns true if value is an odd integer.

.propertyKey(value)

Returns true if value can be used as an object property key (either string, number, or symbol).

.formData(value)

Returns true if value is an instance of the FormData class.

const data = new FormData();

is.formData(data);
//=> true
.urlSearchParams(value)

Returns true if value is an instance of the URLSearchParams class.

const searchParams = new URLSearchParams();

is.urlSearchParams(searchParams);
//=> true
.any(predicate | predicate[], ...values)

Using a single predicate argument, 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

Using an array of predicate[], returns true if any of the input values returns true for any of the predicates provided in an array:

is.any([is.string, is.number], {}, true, '🦄');
//=> true

is.any([is.boolean, is.number], 'unicorns', [], new Map());
//=> false
.all(predicate, ...values)

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

Type guards

When using is together with TypeScript, type guards are being used extensively 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('🦄', '🌈');
//=> '🌈🦄'

Type assertions

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.

import {assert} from '@sindresorhus/is';

const handleMovieRatingApiResponse = (response: unknown) => {
	assert.plainObject(response);
	// `response` is now typed as a plain `object` with `unknown` properties.

	assert.number(response.rating);
	// `response.rating` is now typed as a `number`.

	assert.string(response.title);
	// `response.title` is now typed as a `string`.

	return `${response.title} (${response.rating * 10})`;
};

handleMovieRatingApiResponse({rating: 0.87, title: 'The Matrix'});
//=> 'The Matrix (8.7)'

// This throws an error.
handleMovieRatingApiResponse({rating: '🦄'});

Generic type parameters

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.

import {assert} from '@sindresorhus/is';

async function badNumberAssumption(input: unknown) {
	// Bad assumption about the generic type parameter fools the compile-time type system.
	assert.promise<number>(input);
	// `input` is a `Promise` but only assumed to be `Promise<number>`.

	const resolved = await input;
	// `resolved` is typed as `number` but was not actually checked at runtime.

	// Multiplication will return NaN if the input promise did not actually contain a number.
	return 2 * resolved;
}

async function goodNumberAssertion(input: unknown) {
	assert.promise(input);
	// `input` is typed as `Promise<unknown>`

	const resolved = await input;
	// `resolved` is typed as `unknown`

	assert.number(resolved);
	// `resolved` is typed as `number`

	// Uses runtime checks so only numbers will reach the multiplication.
	return 2 * resolved;
}

badNumberAssumption(Promise.resolve('An unexpected string'));
//=> NaN

// This correctly throws an error because of the unexpected string value.
goodNumberAssertion(Promise.resolve('An unexpected string'));

FAQ

Why yet another type checking module?

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.

Why not just use 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.

For enterprise

Available as part of the Tidelift Subscription.

The maintainers of @sindresorhus/is and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Related

  • ow - Function argument validation for humans
  • 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
  • is-blob - Check if a value is a Blob - File-like object of immutable, raw data
  • has-emoji - Check whether a string has any emoji

Maintainers

More Repositories

1

awesome

😎 Awesome lists about all kinds of interesting topics
270,042
star
2

awesome-nodejs

⚡ Delightful Node.js packages and resources
52,854
star
3

awesome-electron

Useful resources for creating apps with Electron
25,634
star
4

quick-look-plugins

List of useful Quick Look plugins for developers
17,497
star
5

got

🌐 Human-friendly and powerful HTTP request library for Node.js
TypeScript
14,218
star
6

type-fest

A collection of essential TypeScript types
TypeScript
14,015
star
7

ky

🌳 Tiny & elegant JavaScript HTTP client based on the Fetch API
TypeScript
13,762
star
8

pure

Pretty, minimal and fast ZSH prompt
Shell
12,391
star
9

pageres

Capture website screenshots
TypeScript
9,573
star
10

ora

Elegant terminal spinner
JavaScript
8,591
star
11

np

A better `npm publish`
JavaScript
7,529
star
12

github-markdown-css

The minimal amount of CSS to replicate the GitHub Markdown style
CSS
7,421
star
13

caprine

Elegant Facebook Messenger desktop app
TypeScript
7,014
star
14

screenfull

Simple wrapper for cross-browser usage of the JavaScript Fullscreen API
HTML
6,891
star
15

Gifski

🌈 Convert videos to high-quality GIFs on your Mac
Swift
6,807
star
16

fkill-cli

Fabulously kill processes. Cross-platform.
JavaScript
6,782
star
17

query-string

Parse and stringify URL query strings
JavaScript
6,453
star
18

execa

Process execution for humans
JavaScript
6,019
star
19

modern-normalize

🐒 Normalize browsers' default style
TypeScript
5,038
star
20

css-in-readme-like-wat

Style your readme using CSS with this simple trick
5,013
star
21

awesome-npm

Awesome npm resources and tips
4,315
star
22

promise-fun

Promise packages, patterns, chat, and tutorials
4,277
star
23

awesome-scifi

Sci-Fi worth consuming
4,268
star
24

electron-store

Simple data persistence for your Electron app or module - Save and load user preferences, app state, cache, etc
JavaScript
4,165
star
25

create-dmg

Create a good-looking DMG for your macOS app in seconds
JavaScript
3,950
star
26

speed-test

Test your internet connection speed and ping using speedtest.net from the CLI
JavaScript
3,882
star
27

eslint-plugin-unicorn

More than 100 powerful ESLint rules
JavaScript
3,877
star
28

ow

Function argument validation for humans
TypeScript
3,799
star
29

file-type

Detect the file type of a file, stream, or data
JavaScript
3,632
star
30

meow

🐈 CLI app helper
JavaScript
3,305
star
31

p-queue

Promise queue with concurrency control
TypeScript
3,202
star
32

open

Open stuff like URLs, files, executables. Cross-platform.
JavaScript
2,976
star
33

Plash

💦 Make any website your Mac desktop wallpaper
Swift
2,735
star
34

alfy

Create Alfred workflows with ease
JavaScript
2,570
star
35

trash

Move files and directories to the trash
JavaScript
2,512
star
36

fast-cli

Test your download and upload speed using fast.com
JavaScript
2,484
star
37

guides

A collection of succinct guides - Public Domain
2,424
star
38

globby

User-friendly glob matching
JavaScript
2,376
star
39

slugify

Slugify a string
JavaScript
2,357
star
40

emoj

Find relevant emoji from text on the command-line 😮 ✨ 🙌 🐴 💥 🙈
JavaScript
2,311
star
41

cli-spinners

Spinners for use in the terminal
JavaScript
2,255
star
42

on-change

Watch an object or array for changes
JavaScript
1,966
star
43

devtools-detect

Detect if DevTools is open and its orientation
HTML
1,924
star
44

gulp-imagemin

Minify PNG, JPEG, GIF and SVG images
JavaScript
1,903
star
45

touch-bar-simulator

Use the Touch Bar on any Mac
Swift
1,900
star
46

notifier-for-github

Browser extension - Get notified about new GitHub notifications
JavaScript
1,828
star
47

editorconfig-sublime

Sublime Text plugin for EditorConfig - Helps developers maintain consistent coding styles between different editors
Python
1,757
star
48

emittery

Simple and modern async event emitter
JavaScript
1,721
star
49

capture-website

Capture screenshots of websites
JavaScript
1,670
star
50

Defaults

💾 Swifty and modern UserDefaults
Swift
1,661
star
51

electron-boilerplate

Boilerplate to kickstart creating an app with Electron
JavaScript
1,632
star
52

pageres-cli

Capture website screenshots
JavaScript
1,620
star
53

clipboardy

Access the system clipboard (copy/paste)
JavaScript
1,598
star
54

gulp-rev

Static asset revisioning by appending content hash to filenames: `unicorn.css` → `unicorn-d41d8cd98f.css`
JavaScript
1,538
star
55

pify

Promisify a callback-style function
JavaScript
1,494
star
56

boxen

Create boxes in the terminal
JavaScript
1,467
star
57

Actions

⚙️ Supercharge your shortcuts
Swift
1,437
star
58

multiline

Multiline strings in JavaScript
JavaScript
1,424
star
59

hyper-snazzy

Elegant Hyper theme with bright colors
JavaScript
1,412
star
60

amas

Awesome & Marvelous Amas
1,392
star
61

LaunchAtLogin

Add “Launch at Login” functionality to your macOS app in seconds
Swift
1,346
star
62

del

Delete files and directories
JavaScript
1,316
star
63

refined-twitter

Browser extension that simplifies the Twitter interface and adds useful features
JavaScript
1,313
star
64

KeyboardShortcuts

⌨️ Add user-customizable global keyboard shortcuts (hotkeys) to your macOS app in minutes
Swift
1,313
star
65

iterm2-snazzy

Elegant iTerm2 theme with bright colors
1,313
star
66

electron-context-menu

Context menu for your Electron app
JavaScript
1,297
star
67

p-limit

Run multiple promise-returning & async functions with limited concurrency
JavaScript
1,294
star
68

Settings

⚙ Add a settings window to your macOS app in minutes
Swift
1,282
star
69

trash-cli

Move files and folders to the trash
JavaScript
1,244
star
70

electron-util

Useful utilities for Electron apps and modules
JavaScript
1,188
star
71

is-online

Check if the internet connection is up
JavaScript
1,181
star
72

ponyfill

🦄 Like polyfill but with pony pureness
1,136
star
73

conf

Simple config handling for your app or module
TypeScript
1,109
star
74

anatine

[DEPRECATED] 🐦 Pristine Twitter app
JavaScript
1,097
star
75

electron-dl

Simplified file downloads for your Electron app
JavaScript
1,087
star
76

log-update

Log by overwriting the previous output in the terminal. Useful for rendering progress bars, animations, etc.
JavaScript
1,027
star
77

pretty-bytes

Convert bytes to a human readable string: 1337 → 1.34 kB
JavaScript
1,022
star
78

grunt-sass

Compile Sass to CSS
JavaScript
1,020
star
79

mem

Memoize functions - an optimization technique used to speed up consecutive function calls by caching the result of calls with identical input
TypeScript
1,019
star
80

DockProgress

Show progress in your app's Dock icon
Swift
1,003
star
81

wallpaper

Manage the desktop wallpaper
JavaScript
996
star
82

p-map

Map over promises concurrently
JavaScript
996
star
83

public-ip

Get your public IP address - very fast!
JavaScript
979
star
84

gulp-app

[DEPRECATED] Gulp as an app
JavaScript
961
star
85

grunt-shell

Run shell commands
JavaScript
952
star
86

load-grunt-tasks

Load multiple grunt tasks using globbing patterns
JavaScript
940
star
87

hasha

Hashing made simple. Get the hash of a buffer/string/stream/file.
JavaScript
934
star
88

pretty-ms

Convert milliseconds to a human readable string: `1337000000` → `15d 11h 23m 20s`
JavaScript
929
star
89

terminal-image

Display images in the terminal
JavaScript
923
star
90

object-assign

ES2015 Object.assign() ponyfill
JavaScript
922
star
91

copy-text-to-clipboard

Copy text to the clipboard in modern browsers (0.2 kB)
JavaScript
858
star
92

System-Color-Picker

🎨 The macOS color picker as an app with more features
Swift
842
star
93

normalize-url

Normalize a URL
JavaScript
818
star
94

get-port

Get an available TCP port
JavaScript
817
star
95

atom-editorconfig

Helps developers maintain consistent coding styles between different editors
JavaScript
811
star
96

grunt-concurrent

Run grunt tasks concurrently
JavaScript
799
star
97

dot-prop

Get, set, or delete a property from a nested object using a dot path
JavaScript
777
star
98

p-progress

Create a promise that reports progress
TypeScript
751
star
99

gulp-changed

Only pass through changed files
JavaScript
747
star
100

generator-nm

Scaffold out a node module
JavaScript
742
star