Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Type check values

License

NotificationsYou must be signed in to change notification settings

sindresorhus/is

Type check values

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

Highlights

Install

npm install @sindresorhus/is

Usage

importisfrom'@sindresorhus/is';is('🦄');//=> 'string'is(newMap());//=> '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`.

Assertions (exceptassertAll andassertAny) also support an optional custom error message.

import{assert}from'@sindresorhus/is';assert.nonEmptyString(process.env.API_URL,'The API_URL environment variable is required.');//=> Error: The API_URL environment variable is required.

And with TypeScript:

import{assert}from'@sindresorhus/is';assert.string(foo);// `foo` is now typed as a `string`.

Named exports

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 eitheris orassert depending on usage.

For example:

import{assertNull,isUndefined}from'@sindresorhus/is';

API

is(value)

Returns the type ofvalue.

Primitives are lowercase and object types are camelcase.

Example:

  • 'undefined'
  • 'null'
  • 'string'
  • 'symbol'
  • 'Array'
  • 'Function'
  • 'Object'

This method is also exported asdetect. You can import it like this:

import{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 examplenew String('foo').

is.{method}

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

Primitives

.undefined(value)
.null(value)
.string(value)
.number(value)

Note:is.number(NaN) returnsfalse. This intentionally deviates fromtypeof behavior to increase user-friendliness ofis type checks.

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

Built-in types

.array(value, assertion?)

Returns true ifvalue 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)
.buffer(value)
.blob(value)
.object(value)

Keep in mind thatfunctions are objects too.

.numericString(value)

Returnstrue for a string that represents a number satisfyingis.number, for example,'42' and'-8.3'.

Note:'NaN' returnsfalse, but'Infinity' and'-Infinity' returntrue.

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

Returnstrue 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)

Returnstrue for any object that implements its own.next() and.throw() methods and has a function definition forSymbol.iterator.

.generatorFunction(value)
.asyncFunction(value)

Returnstrue for anyasync function that can be called with theawait operator.

is.asyncFunction(async()=>{});//=> trueis.asyncFunction(()=>{});//=> false
.asyncGenerator(value)
is.asyncGenerator((asyncfunction*(){yield4;})());//=> trueis.asyncGenerator((function*(){yield4;})());//=> false
.asyncGeneratorFunction(value)
is.asyncGeneratorFunction(asyncfunction*(){yield4;});//=> trueis.asyncGeneratorFunction(function*(){yield4;});//=> false
.boundFunction(value)

Returnstrue for anybound function.

is.boundFunction(()=>{});//=> trueis.boundFunction(function(){}.bind(null));//=> trueis.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. Returnstrue ifvalue is a member ofenum.

enumDirection{Ascending='ascending',Descending='descending'}is.enumCase('ascending',Direction);//=> trueis.enumCase('other',Direction);//=> false

Emptiness

.emptyString(value)

Returnstrue if the value is astring and the.length is 0.

.emptyStringOrWhitespace(value)

Returnstrue ifis.emptyString(value) or if it's astring that is all whitespace.

.nonEmptyString(value)

Returnstrue if the value is astring and the.length is more than 0.

.nonEmptyStringAndNotWhitespace(value)

Returnstrue if the value is astring that is not empty and not whitespace.

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

Returnstrue if the value is anArray and the.length is 0.

.nonEmptyArray(value)

Returnstrue if the value is anArray and the.length is more than 0.

.emptyObject(value)

Returnstrue if the value is anObject andObject.keys(value).length is 0.

Please note thatObject.keys returns only own enumerable properties. Hence something like this can happen:

constobject1={};Object.defineProperty(object1,'property1',{value:42,writable:true,enumerable:false,configurable:true});is.emptyObject(object1);//=> true
.nonEmptyObject(value)

Returnstrue if the value is anObject andObject.keys(value).length is more than 0.

.emptySet(value)

Returnstrue if the value is aSet and the.size is 0.

.nonEmptySet(Value)

Returnstrue if the value is aSet and the.size is more than 0.

.emptyMap(value)

Returnstrue if the value is aMap and the.size is 0.

.nonEmptyMap(value)

Returnstrue if the value is aMap and the.size is more than 0.

Miscellaneous

.directInstanceOf(value, class)

Returnstrue ifvalue is a direct instance ofclass.

is.directInstanceOf(newError(),Error);//=> trueclassUnicornErrorextendsError{}is.directInstanceOf(newUnicornError(),Error);//=> false
.urlInstance(value)

Returnstrue ifvalue is an instance of theURL class.

consturl=newURL('https://example.com');is.urlInstance(url);//=> true
.urlString(value)

Returnstrue ifvalue is a URL string.

Note: this only does basic checking using theURL class constructor.

consturl='https://example.com';is.urlString(url);//=> trueis.urlString(newURL(url));//=> false
.truthy(value)

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

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

Returnstrue ifvalue 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
  • bigint
.integer(value)
.safeInteger(value)

Returnstrue ifvalue is asafe integer.

.plainObject(value)

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

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

Returnstrue if the value is a class constructor.

.typedArray(value)
.arrayLike(value)

Avalue is array-like if it is not a function and has avalue.length that is a safe integer greater than or equal to 0.

is.arrayLike(document.forms);//=> truefunctionfoo(){is.arrayLike(arguments);//=> true}foo();
.tupleLike(value, guards)

Avalue is tuple-like if it matches the providedguards array both in.length and in types.

is.tupleLike([1],[is.number]);//=> true
functionfoo(){consttuple=[1,'2',true];if(is.tupleLike(tuple,[is.number,is.string,is.boolean])){tuple// [number, string, boolean]}}foo();
.positiveNumber(value)

Check ifvalue is a number and is more than 0.

.negativeNumber(value)

Check ifvalue is a number and is less than 0.

.inRange(value, range)

Check ifvalue (number) is in the givenrange. 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 ifvalue (number) is in the range of0 toupperBound.

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

Returnstrue ifvalue is anHTMLElement.

.nodeStream(value)

Returnstrue ifvalue is a Node.jsstream.

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

Returnstrue ifvalue is anObservable.

import{Observable}from'rxjs';is.observable(newObservable());//=> true
.infinite(value)

Check ifvalue isInfinity or-Infinity.

.evenInteger(value)

Returnstrue ifvalue is an even integer.

.oddInteger(value)

Returnstrue ifvalue is an odd integer.

.propertyKey(value)

Returnstrue ifvalue can be used as an object property key (eitherstring,number, orsymbol).

.formData(value)

Returnstrue ifvalue is an instance of theFormData class.

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

Returnstrue ifvalue is an instance of theURLSearchParams class.

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

Using a singlepredicate argument, returnstrue ifany of the inputvalues returns true in thepredicate:

is.any(is.string,{},true,'🦄');//=> trueis.any(is.boolean,'unicorns',[],newMap());//=> false

Using an array ofpredicate[], returnstrue ifany of the inputvalues returns true forany of thepredicates provided in an array:

is.any([is.string,is.number],{},true,'🦄');//=> trueis.any([is.boolean,is.number],'unicorns',[],newMap());//=> false
.all(predicate, ...values)

Returnstrue ifall of the inputvalues returns true in thepredicate:

is.all(is.object,{},newMap(),newSet());//=> trueis.all(is.string,'🦄',[],'unicorns');//=> false
.optional(value, predicate)

Returnstrue ifvalue isundefined or satisfies the givenpredicate.

is.optional(undefined,is.string);//=> trueis.optional('🦄',is.string);//=> trueis.optional(123,is.string);//=> false
.validDate(value)

Returnstrue if the value is a valid date.

AllDate objects have an internal timestamp value which is the number of milliseconds since theUnix epoch. When a newDate is constructed with bad inputs, no error is thrown. Instead, a newDate object is returned. But the internal timestamp value is set toNaN, 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.

constvalid=newDate('2000-01-01');is.date(valid);//=> truevalid.getTime();//=> 946684800000valid.toUTCString();//=> 'Sat, 01 Jan 2000 00:00:00 GMT'is.validDate(valid);//=> trueconstinvalid=newDate('Not a parsable date string');is.date(invalid);//=> trueinvalid.getTime();//=> NaNinvalid.toUTCString();//=> 'Invalid Date'is.validDate(invalid);//=> false
.validLength(value)

Returnstrue 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.

.whitespaceString(value)

Returnstrue if the value is a string with only whitespace characters.

Type guards

When usingis together with TypeScript,type guards are being used extensively to infer the correct type inside if-else statements.

importisfrom'@sindresorhus/is';constpadLeft=(value:string,padding:string|number)=>{if(is.number(padding)){// `padding` is typed as `number`returnArray(padding+1).join(' ')+value;}if(is.string(padding)){// `padding` is typed as `string`returnpadding+value;}thrownewTypeError(`Expected 'padding' to be of type 'string' or 'number', got '${is(padding)}'.`);}padLeft('🦄',3);//=> '   🦄'padLeft('🦄','🌈');//=> '🌈🦄'

Type assertions

The type guards are also available astype 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';consthandleMovieRatingApiResponse=(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:'🦄'});

Optional assertion

Asserts thatvalue isundefined or satisfies the providedassertion.

import{assert}from'@sindresorhus/is';assert.optional(undefined,assert.string);// Passes without throwingassert.optional('🦄',assert.string);// Passes without throwingassert.optional(123,assert.string);// Throws: Expected value which is `string`, received value of type `number`

Generic type parameters

The type guards and type assertions are aware ofgeneric type parameters, such asPromise<T> andMap<Key, Value>. The default isunknown for most cases, sinceis 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 byis at runtime. This can lead to unexpected behavior, where the generic type isassumed at compile-time, but actually is something completely different at runtime. It is best to useunknown (default) and type-check the value of the generic type parameter at runtime withis orassert.

import{assert}from'@sindresorhus/is';asyncfunctionbadNumberAssumption(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>`.constresolved=awaitinput;// `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.return2*resolved;}asyncfunctiongoodNumberAssertion(input:unknown){assert.promise(input);// `input` is typed as `Promise<unknown>`constresolved=awaitinput;// `resolved` is typed as `unknown`assert.number(resolved);// `resolved` is typed as `number`// Uses runtime checks so only numbers will reach the multiplication.return2*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 usinginstanceof for type checking, forgetting that functions are objects, and omittingsymbol as a primitive.

Why not just useinstanceof instead of this package?

instanceof does not work correctly for all types and it does not work acrossrealms. Examples of realms are iframes, windows, web workers, and thevm module in Node.js.

Related

Maintainers


[8]ページ先頭

©2009-2025 Movatter.jp