Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

43 Commits

Repository files navigation

Improved JavaScript Type Testing

A robust alternative to type testing in vanilla JavaScript. Uses an expanded set of type names to simplify common tests.

See the test page for examples.

Version 4 is not backwards compatible.

Syntax

is(value)

The return value is an object that describes the argument.

MemberDescription
.typeThe type name of value.
.of(class)Tests if value is an instance of class.
.all(...descriptors)Takes descriptor names as arguments. Returns true if all of them apply to value.
.any(...descriptors)Takes descriptor names as arguments. Returns true if any of them apply to value.
[descriptor]Each descriptor property is a boolean that is true if it applies to value.

Enumerable properties of is are string constants of all the descriptor names. These can be used in the .all() and .any() methods instead of string literals. For example, these are equivalent:

is(value).all("number", "object")

is(value).all(is.number, is.object)

Types and Descriptors

Types in this module do not distinguish between primitives and objects. For example, 5 and new Number(5) are both of type "number".

A descriptor is a boolean value that is true if it applies to the value being tested. Type names are included as descriptors. For example, 5 is associated with the primitive, number, and finite descriptors, among others.

DescriptorType NamePrimitive ValuesInstances Of Classes
definednot undefinedObject
undefinedyesundefined
primitiveany primitive value
objectyes1Object
objectishnullObject
nullyesnull
nullishundefined, null
booleanyesfalse, true
falsefalse
truetrue
falsyundefined, null, false, 0n, NaN, 0, ""
truthynot a falsy valueObject
symbolyesa Symbol
bigintyes0n, 5n
numberish0, 5, Infinity, NaNNumber
nanyesNaNNumber with value NaN
numberyes0, 5, InfinityNumber excluding those with value NaN
real20, 5Number with a finite number value
finite0, 5Number with a finite number value
infiniteInfinityNumber with an infinite value
stringyes"", "foo"String
arrayyes[], [1,2]Array
mapyesMap
setyesSet
weakmapyesWeakMap
weaksetyesWeakSet
empty"", []String or Array with .length === 0,
Map or Set with .size === 0
nonempty"foo", [1,2]String or Array with .length > 0,
Map or Set with .size > 0
dateyesDate
erroryesError
functionyesFunction
promiseyesPromise
regexyesRegex

Footnotes

  1. The "object" type is only used for a value if no other type is appropriate.

  2. Deprecated. Use finite instead.

About

Improved JavaScript type testing

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages