diff --git a/.gitattributes b/.gitattributes index 391f0a4..6313b56 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1 @@ -* text=auto -*.js text eol=lf +* text=auto eol=lf diff --git a/.github/security.md b/.github/security.md new file mode 100644 index 0000000..5358dc5 --- /dev/null +++ b/.github/security.md @@ -0,0 +1,3 @@ +# Security Policy + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..33db234 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,21 @@ +name: CI +on: + - push + - pull_request +jobs: + test: + name: Node.js ${{ matrix.node-version }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: + - 24 + - 22 + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-node@v6 + with: + node-version: ${{ matrix.node-version }} + - run: npm install + - run: npm test diff --git a/.gitignore b/.gitignore index 239ecff..eb99a21 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ node_modules yarn.lock +/distribution +.tsimp diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 7d69d74..0000000 --- a/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - '8' - - '6' - - '4' diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..2996cf5 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,9 @@ +# Notes + +## Branded types for type guards + +TypeScript type guards narrow in both branches. If `is.integer(n)` returns `value is number` and the input is `number`, the false branch computes `Exclude` = `never`. This makes common patterns like `if (!is.integer(n)) throw; use(n)` fail because `n` becomes `never` after the guard. + +To avoid this, type guard predicates use branded types (e.g., `number & {readonly __brand: 'Integer'}`, `string & {readonly __brand: 'UrlString'}`). A branded subtype ensures the false branch stays the original type (e.g., `Exclude` = `number`). + +Assert functions (`asserts value is T`) don't need branded types since they throw on failure and have no false branch. They use plain types like `asserts value is number`. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 0000000..47dc3e3 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/index.js b/index.js deleted file mode 100644 index 132db41..0000000 --- a/index.js +++ /dev/null @@ -1,151 +0,0 @@ -'use strict'; -const toString = Object.prototype.toString; -const getObjectType = x => toString.call(x).slice(8, -1); - -const is = value => { - if (value == null) { // eslint-disable-line no-eq-null, eqeqeq - return 'null'; - } - - if (value === true || value === false) { - return 'boolean'; - } - - const type = typeof value; - - if (type === 'undefined') { - return 'undefined'; - } - - if (type === 'string') { - return 'string'; - } - - if (type === 'number') { - return 'number'; - } - - if (type === 'symbol') { - return 'symbol'; - } - - if (type === 'function') { - return 'Function'; - } - - if (Array.isArray(value)) { - return 'Array'; - } - - if (Buffer.isBuffer(value)) { - return 'Buffer'; - } - - const tagType = getObjectType(value); - if (tagType) { - return tagType; - } - - if (value instanceof String || value instanceof Boolean || value instanceof Number) { - throw new TypeError('Please don\'t use object wrappers for primitive types'); - } - - return 'Object'; -}; - -is.undefined = x => typeof x === 'undefined'; -is.null = x => x === null; -is.string = x => typeof x === 'string'; -is.number = x => typeof x === 'number'; -is.boolean = x => typeof x === 'boolean'; -is.symbol = x => typeof x === 'symbol'; - -is.array = Array.isArray; -is.function = x => typeof x === 'function'; -is.buffer = Buffer.isBuffer; - -is.object = x => { - const type = typeof x; - return x !== null && (type === 'object' || type === 'function'); -}; - -is.nativePromise = x => getObjectType(x) === 'Promise'; - -is.promise = x => { - return is.nativePromise(x) || - ( - x !== null && - typeof x === 'object' && - typeof x.then === 'function' && - typeof x.catch === 'function' - ); -}; - -is.regExp = x => getObjectType(x) === 'RegExp'; -is.date = x => getObjectType(x) === 'Date'; -is.error = x => getObjectType(x) === 'Error'; -is.map = x => getObjectType(x) === 'Map'; -is.set = x => getObjectType(x) === 'Set'; -is.weakMap = x => getObjectType(x) === 'WeakMap'; -is.weakSet = x => getObjectType(x) === 'WeakSet'; - -is.int8Array = x => getObjectType(x) === 'Int8Array'; -is.uint8Array = x => getObjectType(x) === 'Uint8Array'; -is.uint8ClampedArray = x => getObjectType(x) === 'Uint8ClampedArray'; -is.int16Array = x => getObjectType(x) === 'Int16Array'; -is.uint16Array = x => getObjectType(x) === 'Uint16Array'; -is.int32Array = x => getObjectType(x) === 'Int32Array'; -is.uint32Array = x => getObjectType(x) === 'Uint32Array'; -is.float32Array = x => getObjectType(x) === 'Float32Array'; -is.float64Array = x => getObjectType(x) === 'Float64Array'; - -is.arrayBuffer = x => getObjectType(x) === 'ArrayBuffer'; - -is.sharedArrayBuffer = x => { - try { - return getObjectType(x) === 'SharedArrayBuffer'; - } catch (err) { - return false; - } -}; - -is.nan = Number.isNaN; -is.nullOrUndefined = x => x === null || typeof x === 'undefined'; - -is.primitive = x => { - const type = typeof x; - return x === null || - type === 'undefined' || - type === 'string' || - type === 'number' || - type === 'boolean' || - type === 'symbol'; -}; - -is.integer = Number.isInteger; - -is.plainObject = x => { - // From: https://github.com/sindresorhus/is-plain-obj/blob/master/index.js - let prototype; - // eslint-disable-next-line no-return-assign - return getObjectType(x) === 'Object' && - (prototype = Object.getPrototypeOf(x), prototype === null || - prototype === Object.getPrototypeOf({})); -}; - -is.iterable = x => !is.null(x) && !is.undefined(x) && typeof x[Symbol.iterator] === 'function'; - -const typedArrayTypes = new Set([ - 'Int8Array', - 'Uint8Array', - 'Uint8ClampedArray', - 'Int16Array', - 'Uint16Array', - 'Int32Array', - 'Uint32Array', - 'Float32Array', - 'Float64Array' -]); -is.typedArray = x => typedArrayTypes.has(getObjectType(x)); - -module.exports = is; diff --git a/license b/license index e7af2f7..fa7ceba 100644 --- a/license +++ b/license @@ -1,6 +1,6 @@ MIT License -Copyright (c) Sindre Sorhus (sindresorhus.com) +Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: diff --git a/package.json b/package.json index 0085cc1..d7a386f 100644 --- a/package.json +++ b/package.json @@ -1,49 +1,76 @@ { - "name": "@sindresorhus/is", - "version": "0.1.0", - "description": "Type check values: `is.string('🦄') //=> true`", - "license": "MIT", - "repository": "sindresorhus/is", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "publishConfig": { - "access": "public" - }, - "engines": { - "node": ">=4" - }, - "scripts": { - "test": "xo && ava" - }, - "files": [ - "index.js" - ], - "keywords": [ - "type", - "types", - "is", - "check", - "checking", - "validate", - "validation", - "utility", - "util", - "typeof", - "instanceof", - "object", - "assert", - "assertion", - "test", - "kind", - "primitive", - "verify", - "compare" - ], - "devDependencies": { - "ava": "*", - "xo": "*" - } + "name": "@sindresorhus/is", + "version": "8.1.0", + "description": "Type check values", + "license": "MIT", + "repository": "sindresorhus/is", + "funding": "https://github.com/sindresorhus/is?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": { + "types": "./distribution/index.d.ts", + "default": "./distribution/index.js" + }, + "sideEffects": false, + "engines": { + "node": ">=22" + }, + "scripts": { + "build": "del distribution && tsc", + "test": "tsc --noEmit && tsc --project test/tsconfig.json --noEmit && xo && node --experimental-transform-types --test test/test.ts", + "prepare": "npm run build" + }, + "files": [ + "distribution" + ], + "keywords": [ + "type", + "types", + "is", + "check", + "checking", + "validate", + "validation", + "utility", + "util", + "typeof", + "instanceof", + "object", + "assert", + "assertion", + "test", + "kind", + "primitive", + "verify", + "compare", + "typescript", + "typeguards", + "types" + ], + "xo": { + "rules": { + "@typescript-eslint/no-unsafe-enum-comparison": "off", + "@typescript-eslint/no-confusing-void-expression": "off", + "@typescript-eslint/no-unsafe-type-assertion": "off", + "@stylistic/operator-linebreak": "off" + } + }, + "devDependencies": { + "@sindresorhus/tsconfig": "^8.1.0", + "@types/jsdom": "^28.0.1", + "@types/node": "^25.5.2", + "@types/zen-observable": "^0.8.7", + "del-cli": "^7.0.0", + "expect-type": "^1.3.0", + "jsdom": "^29.0.2", + "rxjs": "^7.8.2", + "tempy": "^3.2.0", + "typescript": "6.0.2", + "xo": "^2.0.2", + "zen-observable": "^0.10.0" + } } diff --git a/readme.md b/readme.md index ee1761d..509f75f 100644 --- a/readme.md +++ b/readme.md @@ -1,21 +1,30 @@ -# is [![Build Status](https://travis-ci.org/sindresorhus/is.svg?branch=master)](https://travis-ci.org/sindresorhus/is) +# is -> Type check values: `is.string('🦄') //=> true` +> Type check values + +For example, `is.string('🦄') //=> true` +## Highlights + +- Written in TypeScript +- [Extensive use of type guards](#type-guards) +- [Supports type assertions](#type-assertions) +- [Aware of generic type parameters](#generic-type-parameters) (use with caution) +- Actively maintained +- ![Millions of downloads per week](https://img.shields.io/npm/dw/@sindresorhus/is) ## Install +```sh +npm install @sindresorhus/is ``` -$ npm install @sindresorhus/is -``` - ## Usage ```js -const is = require('@sindresorhus/is'); +import is from '@sindresorhus/is'; is('🦄'); //=> 'string' @@ -27,6 +36,44 @@ is.number(6); //=> true ``` +[Assertions](#type-assertions) perform the same type checks, but throw an error if the type does not match. + +```js +import {assert} from '@sindresorhus/is'; + +assert.string(2); +//=> Error: Expected value which is `string`, received value of type `number`. +``` + +Assertions (except `assertAll` and `assertAny`) also support an optional custom error message. + +```js +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: + +```ts +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 either `is` or `assert` depending on usage. + +For example: + +```js +import {assertNull, isUndefined} from '@sindresorhus/is'; +``` ## API @@ -46,30 +93,72 @@ Example: - `'Function'` - `'Object'` -Note: It will throw if you try to feed it object-wrapped primitives, as that's a bad practice. For example `new String('foo')`. +This method is also exported as `detect`. You can import it like this: + +```js +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 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. +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)` 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) +##### .array(value, assertion?) + +Returns true if `value` is an array and all of its items match the assertion (if provided). + +```js +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. +``` + +##### .arrayOf(predicate) + +Returns a type guard that checks if `value` is an array where every item matches the predicate. Useful for composing with other methods. + +```js +const isStringArray = is.arrayOf(is.string); + +isStringArray(['a', 'b']); //=> true +isStringArray(['a', 1]); //=> false +``` + ##### .function(value) + ##### .buffer(value) + +> [!NOTE] +> [Prefer using `Uint8Array` instead of `Buffer`.](https://sindresorhus.com/blog/goodbye-nodejs-buffer) + +##### .blob(value) ##### .object(value) Keep in mind that [functions are objects too](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions). +##### .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) @@ -78,10 +167,76 @@ Keep in mind that [functions are objects too](https://developer.mozilla.org/en-U 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. + +```js +is.asyncFunction(async () => {}); +//=> true + +is.asyncFunction(() => {}); +//=> false +``` + +##### .asyncGenerator(value) + +```js +is.asyncGenerator( + (async function * () { + yield 4; + })() +); +//=> true + +is.asyncGenerator( + (function * () { + yield 4; + })() +); +//=> false +``` + +##### .asyncGeneratorFunction(value) + +```js +is.asyncGeneratorFunction(async function * () { + yield 4; +}); +//=> true + +is.asyncGeneratorFunction(function * () { + yield 4; +}); +//=> false +``` + +##### .boundFunction(value) + +Returns `true` for any `bound` function. + +```js +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 @@ -94,6 +249,8 @@ Returns `true` for any object with a `.then()` and `.catch()` method. Prefer thi ##### .uint32Array(value) ##### .float32Array(value) ##### .float64Array(value) +##### .bigInt64Array(value) +##### .bigUint64Array(value) #### Structured data @@ -101,22 +258,630 @@ Returns `true` for any object with a `.then()` and `.catch()` method. Prefer thi ##### .sharedArrayBuffer(value) ##### .dataView(value) +##### .enumCase(value, enum) + +TypeScript-only. Returns `true` if `value` is a member of `enum`. + +```ts +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. + +```js +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: + +```js +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`. + +```js +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](https://developer.mozilla.org/en-US/docs/Web/API/URL). + +```js +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](https://developer.mozilla.org/en-US/docs/Web/API/URL) constructor. + +```js +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: + +```js +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`. +JavaScript primitives are as follows: + +- `null` +- `undefined` +- `string` +- `number` +- `boolean` +- `symbol` +- `bigint` ##### .integer(value) + +##### .safeInteger(value) + +Returns `true` if `value` is a [safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + ##### .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` if the value is a class constructor. + ##### .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. + +```js +is.arrayLike(document.forms); +//=> true + +function foo() { + is.arrayLike(arguments); + //=> true +} +foo(); +``` + +##### .tupleLike(value, guards) + +A `value` is tuple-like if it matches the provided `guards` array both in `.length` and in types. + +```js +is.tupleLike([1], [is.number]); +//=> true +``` + +```js +function foo() { + const tuple = [1, '2', true]; + if (is.tupleLike(tuple, [is.number, is.string, is.boolean])) { + tuple // [number, string, boolean] + } +} + +foo(); +``` + +##### .finiteNumber(value) + +Check if `value` is a number and is finite. Excludes `Infinity` and `-Infinity`. + +##### .positiveNumber(value) + +Check if `value` is a number and is more than 0. + +##### .negativeNumber(value) + +Check if `value` is a number and is less than 0. + +##### .nonNegativeNumber(value) + +Check if `value` is a number and is 0 or more. + +##### .positiveInteger(value) + +Check if `value` is an integer and is more than 0. + +##### .negativeInteger(value) + +Check if `value` is an integer and is less than 0. + +##### .nonNegativeInteger(value) + +Check if `value` is an integer and is 0 or more. + +##### .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. + +```js +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`. + +```js +is.inRange(3, 10); +``` + +##### .htmlElement(value) + +Returns `true` if `value` is an [HTMLElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement). + +##### .nodeStream(value) + +Returns `true` if `value` is a Node.js [stream](https://nodejs.org/api/stream.html). + +```js +import fs from 'node:fs'; + +is.nodeStream(fs.createReadStream('unicorn.png')); +//=> true +``` + +##### .observable(value) + +Returns `true` if `value` is an `Observable`. + +```js +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](https://developer.mozilla.org/en-US/docs/Web/API/FormData). + +```js +const data = new FormData(); + +is.formData(data); +//=> true +``` + +##### .urlSearchParams(value) + +Returns `true` if `value` is an instance of the [`URLSearchParams` class](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams). + +```js +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`: + +```js +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: + +```js +is.any([is.string, is.number], {}, true, '🦄'); +//=> true + +is.any([is.boolean, is.number], 'unicorns', [], new Map()); +//=> false +``` + +##### .any(predicate[]) + +Using an array of `predicate[]` without values, returns a combined type guard that checks if a value matches **any** of the predicates: + +```js +const isStringOrNumber = is.any([is.string, is.number]); + +isStringOrNumber('hello'); +//=> true + +isStringOrNumber(123); +//=> true + +isStringOrNumber(true); +//=> false +``` + +This is useful for composing with other methods like `is.optional`: + +```js +is.optional(value, is.any([is.string, is.number])); +``` + +An empty predicate array currently returns a predicate that always returns `false`. This will throw in the next major release. + +##### .all(predicate, ...values) + +Returns `true` if **all** of the input `values` returns true in the `predicate`: + +```js +is.all(is.object, {}, new Map(), new Set()); +//=> true + +is.all(is.string, '🦄', [], 'unicorns'); +//=> false +``` + +##### .all(predicate[]) + +Using an array of `predicate[]` without values, returns a combined type guard that checks if a value matches **all** of the predicates: + +```js +const isArrayAndNonEmpty = is.all([is.array, is.nonEmptyArray]); + +isArrayAndNonEmpty(['hello']); +//=> true + +isArrayAndNonEmpty([]); +//=> false +``` + +This is useful for composing with other methods like `is.optional`: + +```js +is.optional(value, is.all([is.object, is.plainObject])); +``` + +An empty predicate array currently returns a predicate that always returns `true`. This will throw in the next major release. + +##### .optional(value, predicate) + +Returns `true` if `value` is `undefined` or satisfies the given `predicate`. + +```js +is.optional(undefined, is.string); +//=> true + +is.optional('🦄', is.string); +//=> true + +is.optional(123, is.string); +//=> false +``` + +##### .oneOf(values) + +Returns a type guard that checks if `value` is one of the given `values`. Best used with `as const` for precise type narrowing. + +```ts +const isDirection = is.oneOf(['north', 'south', 'east', 'west'] as const); + +isDirection('north'); //=> true +isDirection('up'); //=> false +``` + +##### .validDate(value) + +Returns `true` if the value is a valid date. + +All [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) objects have an internal timestamp value which is the number of milliseconds since the [Unix epoch](https://developer.mozilla.org/en-US/docs/Glossary/Unix_time). 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. + +```js +const valid = new Date('2000-01-01'); + +is.date(valid); +//=> true +valid.getTime(); +//=> 946684800000 +valid.toUTCString(); +//=> 'Sat, 01 Jan 2000 00:00:00 GMT' +is.validDate(valid); +//=> true + +const invalid = new Date('Not a parsable date string'); + +is.date(invalid); +//=> true +invalid.getTime(); +//=> NaN +invalid.toUTCString(); +//=> 'Invalid Date' +is.validDate(invalid); +//=> false +``` + +##### .validLength(value) + +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. + +##### .whitespaceString(value) + +Returns `true` if the value is a string with only whitespace characters. + +## Type guards + +When using `is` together with TypeScript, [type guards](http://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types) are being used extensively to infer the correct type inside if-else statements. + +```ts +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](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions), which throw an error for unexpected types. It is a convenient one-line version of the often repetitive "if-not-expected-type-throw" pattern. + +```ts +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: '🦄'}); +``` + +### Negative assertion + +Asserts that `value` is not the specified type. Only exact, type-safe negative assertions are exposed. + +Supported assertions: + +- `assert.not.undefined(value)` +- `assert.not.null(value)` +- `assert.not.nullOrUndefined(value)` +- `assert.not.string(value)` +- `assert.not.boolean(value)` +- `assert.not.symbol(value)` +- `assert.not.bigint(value)` +- `assert.not.primitive(value)` + +This intentionally excludes checks that cannot produce a safe TypeScript complement: `number` because `is.number` rejects `NaN`, refinements such as `integer` and `validDate`, and branded structural object checks such as `map` and `date`. Broad object checks such as `object` are also excluded to keep negative assertions limited to primitive and nullish types. + +```ts +import {assert} from '@sindresorhus/is'; + +const value: string | undefined = getValue(); + +assert.not.undefined(value); +// Throws if `value` is `undefined`. Otherwise, `value` is now typed as `string`. +``` + +For `unknown` input, exact negative assertions narrow to the remaining representable type: + +```ts +const value: unknown = getValue(); + +assert.not.nullOrUndefined(value); +// `value` is now typed as non-nullish. + +assert.not.primitive(value); +// `value` is now typed as `object`. +``` + +### Optional assertion + +Asserts that `value` is `undefined` or satisfies the provided `assertion`. + +```ts +import {assert} from '@sindresorhus/is'; + +assert.optional(undefined, assert.string); +// Passes without throwing + +assert.optional('🦄', assert.string); +// Passes without throwing + +assert.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 of [generic type parameters](https://www.typescriptlang.org/docs/handbook/generics.html), such as `Promise` and `Map`. 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`. + +```ts +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(input); + // `input` is a `Promise` but only assumed to be `Promise`. + + 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` + + 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 @@ -135,9 +900,13 @@ 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](https://stackoverflow.com/a/49832343/64949). Examples of realms are iframes, windows, web workers, and the `vm` module in Node.js. ## Related +- [environment](https://github.com/sindresorhus/environment) - Check which JavaScript environment your code is running in at runtime - [is-stream](https://github.com/sindresorhus/is-stream) - Check if something is a Node.js stream - [is-observable](https://github.com/sindresorhus/is-observable) - Check if a value is an Observable - [file-type](https://github.com/sindresorhus/file-type) - Detect the file type of a Buffer/Uint8Array @@ -145,8 +914,11 @@ The most common mistakes I noticed in these modules was using `instanceof` for t - [is-array-sorted](https://github.com/sindresorhus/is-array-sorted) - Check if an Array is sorted - [is-error-constructor](https://github.com/sindresorhus/is-error-constructor) - Check if a value is an error constructor - [is-empty-iterable](https://github.com/sindresorhus/is-empty-iterable) - Check if an Iterable is empty +- [is-blob](https://github.com/sindresorhus/is-blob) - Check if a value is a Blob - File-like object of immutable, raw data +- [has-emoji](https://github.com/sindresorhus/has-emoji) - Check whether a string has any emoji +## Maintainers -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Giora Guttsait](https://github.com/gioragutt) +- [Brandon Smith](https://github.com/brandon93s) diff --git a/source/index.ts b/source/index.ts new file mode 100644 index 0000000..6c2f428 --- /dev/null +++ b/source/index.ts @@ -0,0 +1,2038 @@ +import type { + ArrayLike, + Class, + EvenInteger, + Falsy, + FiniteNumber, + Integer, + NaN as NaNType, + NegativeInfinity, + NegativeInteger, + NegativeNumber, + NodeStream, + NonEmptyString, + NonNegativeInteger, + NonNegativeNumber, + ObservableLike, + OddInteger, + Predicate, + Primitive, + PositiveInfinity, + PositiveInteger, + PositiveNumber, + SafeInteger, + TypedArray, + UrlString, + ValidLength, + WeakRef, + Whitespace, +} from './types.ts'; +import {keysOf} from './utilities.ts'; + +// From type-fest. +type ExtractFromGlobalConstructors = + Name extends string + ? typeof globalThis extends Record infer T> ? T : never + : never; + +type NodeBuffer = ExtractFromGlobalConstructors<'Buffer'>; + +type NumericGuardResult = + ( + unknown extends Input + ? Branded + : Input extends number + ? Branded & Input + : number + ) & Input; + +const typedArrayTypeNames = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array', +] as const; + +type TypedArrayTypeName = typeof typedArrayTypeNames[number]; + +function isTypedArrayName(name: unknown): name is TypedArrayTypeName { + return typedArrayTypeNames.includes(name as TypedArrayTypeName); +} + +const objectTypeNames = [ + 'Function', + 'Generator', + 'AsyncGenerator', + 'GeneratorFunction', + 'AsyncGeneratorFunction', + 'AsyncFunction', + 'Observable', + 'Array', + 'Buffer', + 'Blob', + 'Object', + 'RegExp', + 'Date', + 'Error', + 'Map', + 'Set', + 'WeakMap', + 'WeakSet', + 'WeakRef', + 'ArrayBuffer', + 'SharedArrayBuffer', + 'DataView', + 'Promise', + 'URL', + 'FormData', + 'URLSearchParams', + 'HTMLElement', + 'NaN', + ...typedArrayTypeNames, +] as const; + +type ObjectTypeName = typeof objectTypeNames[number]; + +function isObjectTypeName(name: unknown): name is ObjectTypeName { + return objectTypeNames.includes(name as ObjectTypeName); +} + +const primitiveTypeNames = [ + 'null', + 'undefined', + 'string', + 'number', + 'bigint', + 'boolean', + 'symbol', +] as const; + +type PrimitiveTypeName = typeof primitiveTypeNames[number]; + +function isPrimitiveTypeName(name: unknown): name is PrimitiveTypeName { + return primitiveTypeNames.includes(name as PrimitiveTypeName); +} + +export type TypeName = ObjectTypeName | PrimitiveTypeName; + +const assertionTypeDescriptions = [ + 'bound Function', + 'positive number', + 'negative number', + 'Class', + 'string with a number', + 'null or undefined', + 'Iterable', + 'AsyncIterable', + 'native Promise', + 'EnumCase', + 'string with a URL', + 'truthy', + 'falsy', + 'primitive', + 'integer', + 'plain object', + 'TypedArray', + 'array-like', + 'tuple-like', + 'Node.js Stream', + 'infinite number', + 'empty array', + 'non-empty array', + 'empty string', + 'empty string or whitespace', + 'non-empty string', + 'non-empty string and not whitespace', + 'empty object', + 'non-empty object', + 'empty set', + 'non-empty set', + 'empty map', + 'non-empty map', + 'PropertyKey', + 'even integer', + 'finite number', + 'negative integer', + 'non-negative integer', + 'non-negative number', + 'odd integer', + 'positive integer', + 'safe integer', + 'T', + 'in range', + 'predicate returns truthy for any value', + 'predicate returns truthy for all values', + 'valid Date', + 'valid length', + 'whitespace string', + ...objectTypeNames, + ...primitiveTypeNames, +] as const; + +export type AssertionTypeDescription = typeof assertionTypeDescriptions[number]; + +const getObjectType = (value: unknown): ObjectTypeName | undefined => { + const objectTypeName = Object.prototype.toString.call(value).slice(8, -1); + + if (/HTML\w+Element/v.test(objectTypeName) && isHtmlElement(value)) { + return 'HTMLElement'; + } + + if (isObjectTypeName(objectTypeName)) { + return objectTypeName; + } + + return undefined; +}; + +function detect(value: unknown): TypeName { + if (value === null) { + return 'null'; + } + + // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check + switch (typeof value) { + case 'undefined': { + return 'undefined'; + } + + case 'string': { + return 'string'; + } + + case 'number': { + return Number.isNaN(value) ? 'NaN' : 'number'; + } + + case 'boolean': { + return 'boolean'; + } + + case 'function': { + return 'Function'; + } + + case 'bigint': { + return 'bigint'; + } + + case 'symbol': { + return 'symbol'; + } + + default: + } + + if (isObservable(value)) { + return 'Observable'; + } + + if (isArray(value)) { + return 'Array'; + } + + if (isBuffer(value)) { + return 'Buffer'; + } + + const tagType = getObjectType(value); + if (tagType !== undefined && tagType !== 'Object') { + return tagType; + } + + if (hasPromiseApi(value)) { + return 'Promise'; + } + + if (isBoxedPrimitiveObject(value)) { + throw new TypeError('Please don\'t use object wrappers for primitive types'); + } + + return 'Object'; +} + +function hasPromiseApi(value: unknown): value is Promise { + return isFunction((value as Promise)?.then) && isFunction((value as Promise)?.catch); +} + +function hasBoxedPrimitiveBrand(value: unknown, valueOf: () => unknown): boolean { + try { + // `Object.prototype.toString` can be spoofed via `Symbol.toStringTag`, but the + // boxed primitive `valueOf` methods still enforce the real internal brand. + Reflect.apply(valueOf, value, []); + return true; + } catch { + return false; + } +} + +function isBoxedPrimitiveObject(value: unknown): boolean { + return hasBoxedPrimitiveBrand(value, String.prototype.valueOf) + || hasBoxedPrimitiveBrand(value, Boolean.prototype.valueOf) + || hasBoxedPrimitiveBrand(value, Number.prototype.valueOf); +} + +const is = Object.assign( + detect, + { + all: isAll, + any: isAny, + array: isArray, + arrayBuffer: isArrayBuffer, + arrayLike: isArrayLike, + arrayOf: isArrayOf, + asyncFunction: isAsyncFunction, + asyncGenerator: isAsyncGenerator, + asyncGeneratorFunction: isAsyncGeneratorFunction, + asyncIterable: isAsyncIterable, + bigint: isBigint, + bigInt64Array: isBigInt64Array, + bigUint64Array: isBigUint64Array, + blob: isBlob, + boolean: isBoolean, + boundFunction: isBoundFunction, + buffer: isBuffer, + class: isClass, + dataView: isDataView, + date: isDate, + detect, + directInstanceOf: isDirectInstanceOf, + emptyArray: isEmptyArray, + emptyMap: isEmptyMap, + emptyObject: isEmptyObject, + emptySet: isEmptySet, + emptyString: isEmptyString, + emptyStringOrWhitespace: isEmptyStringOrWhitespace, + enumCase: isEnumCase, + error: isError, + evenInteger: isEvenInteger, + falsy: isFalsy, + finiteNumber: isFiniteNumber, + float32Array: isFloat32Array, + float64Array: isFloat64Array, + formData: isFormData, + function: isFunction, + generator: isGenerator, + generatorFunction: isGeneratorFunction, + htmlElement: isHtmlElement, + infinite: isInfinite, + inRange: isInRange, + int16Array: isInt16Array, + int32Array: isInt32Array, + int8Array: isInt8Array, + integer: isInteger, + iterable: isIterable, + map: isMap, + nan: isNan, + nativePromise: isNativePromise, + negativeInteger: isNegativeInteger, + negativeNumber: isNegativeNumber, + nodeStream: isNodeStream, + nonEmptyArray: isNonEmptyArray, + nonEmptyMap: isNonEmptyMap, + nonEmptyObject: isNonEmptyObject, + nonEmptySet: isNonEmptySet, + nonEmptyString: isNonEmptyString, + nonEmptyStringAndNotWhitespace: isNonEmptyStringAndNotWhitespace, + nonNegativeInteger: isNonNegativeInteger, + nonNegativeNumber: isNonNegativeNumber, + null: isNull, + nullOrUndefined: isNullOrUndefined, + number: isNumber, + numericString: isNumericString, + object: isObject, + observable: isObservable, + oddInteger: isOddInteger, + oneOf: isOneOf, + plainObject: isPlainObject, + positiveInteger: isPositiveInteger, + positiveNumber: isPositiveNumber, + primitive: isPrimitive, + promise: isPromise, + propertyKey: isPropertyKey, + regExp: isRegExp, + safeInteger: isSafeInteger, + set: isSet, + sharedArrayBuffer: isSharedArrayBuffer, + string: isString, + symbol: isSymbol, + truthy: isTruthy, + tupleLike: isTupleLike, + typedArray: isTypedArray, + uint16Array: isUint16Array, + uint32Array: isUint32Array, + uint8Array: isUint8Array, + uint8ClampedArray: isUint8ClampedArray, + undefined: isUndefined, + urlInstance: isUrlInstance, + urlSearchParams: isUrlSearchParams, + urlString: isUrlString, + optional: isOptional, + validDate: isValidDate, + validLength: isValidLength, + weakMap: isWeakMap, + weakRef: isWeakRef, + weakSet: isWeakSet, + whitespaceString: isWhitespaceString, + }, +); + +function isAbsoluteModule2(remainder: 0 | 1) { + return (value: unknown): value is number => isInteger(value) && Math.abs(value % 2) === remainder; +} + +type TypeGuard = (value: unknown) => value is T; + +function validatePredicateArray(predicateArray: readonly Predicate[], allowEmpty: boolean) { + if (predicateArray.length === 0) { + if (allowEmpty) { + // Next major release: throw for empty predicate arrays to avoid vacuous results. + // throw new TypeError('Invalid predicate array'); + } else { + throw new TypeError('Invalid predicate array'); + } + + return; + } + + for (const predicate of predicateArray) { + validatePredicate(predicate); + } +} + +function validatePredicate(predicate: Predicate) { + if (!isFunction(predicate)) { + throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); + } +} + +// Predicate factory overloads - return a type guard when called with only predicates +export function isAll(predicates: [TypeGuard]): TypeGuard; +export function isAll(predicates: [TypeGuard, TypeGuard]): TypeGuard; +export function isAll(predicates: [TypeGuard, TypeGuard, TypeGuard]): TypeGuard; +export function isAll(predicates: [TypeGuard, TypeGuard, TypeGuard, TypeGuard]): TypeGuard; +export function isAll(predicates: [TypeGuard, TypeGuard, TypeGuard, TypeGuard, TypeGuard]): TypeGuard; +export function isAll(predicates: ReadonlyArray>): TypeGuard; +export function isAll(predicates: readonly Predicate[]): Predicate; +// Evaluator overload - check if all values match the predicate +export function isAll(predicate: Predicate | readonly Predicate[], ...values: unknown[]): boolean; +export function isAll(predicate: Predicate | readonly Predicate[], ...values: unknown[]): boolean | Predicate { + if (Array.isArray(predicate)) { + const predicateArray = predicate as readonly Predicate[]; + validatePredicateArray(predicateArray, values.length === 0); + + const combinedPredicate = (value: unknown) => predicateArray.every(singlePredicate => singlePredicate(value)); + if (values.length === 0) { + return combinedPredicate; + } + + return predicateOnArray(Array.prototype.every, combinedPredicate, values); + } + + return predicateOnArray(Array.prototype.every, predicate as Predicate, values); +} + +// Predicate factory overloads - return a type guard when called with only predicates +export function isAny(predicates: [TypeGuard]): TypeGuard; +export function isAny(predicates: [TypeGuard, TypeGuard]): TypeGuard; +export function isAny(predicates: [TypeGuard, TypeGuard, TypeGuard]): TypeGuard; +export function isAny(predicates: [TypeGuard, TypeGuard, TypeGuard, TypeGuard]): TypeGuard; +export function isAny(predicates: [TypeGuard, TypeGuard, TypeGuard, TypeGuard, TypeGuard]): TypeGuard; +export function isAny(predicates: ReadonlyArray>): TypeGuard; +export function isAny(predicates: readonly Predicate[]): Predicate; +// Evaluator overload - check if any value matches any predicate +export function isAny(predicate: Predicate | readonly Predicate[], ...values: unknown[]): boolean; +export function isAny(predicate: Predicate | readonly Predicate[], ...values: unknown[]): boolean | Predicate { + if (Array.isArray(predicate)) { + const predicateArray = predicate as readonly Predicate[]; + validatePredicateArray(predicateArray, values.length === 0); + + const combinedPredicate = (value: unknown) => predicateArray.some(singlePredicate => singlePredicate(value)); + if (values.length === 0) { + return combinedPredicate; + } + + return predicateOnArray(Array.prototype.some, combinedPredicate, values); + } + + return predicateOnArray(Array.prototype.some, predicate as Predicate, values); +} + +export function isOptional(value: unknown, predicate: (value: unknown) => value is T): value is T | undefined { + return isUndefined(value) || predicate(value); +} + +export function isArray(value: unknown, assertion?: (value: T) => value is T): value is T[] { + if (!Array.isArray(value)) { + return false; + } + + if (!isFunction(assertion)) { + return true; + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return value.every(element => assertion(element)); +} + +export function isArrayBuffer(value: unknown): value is ArrayBuffer { + return getObjectType(value) === 'ArrayBuffer'; +} + +export function isArrayLike(value: unknown): value is ArrayLike { + return !isNullOrUndefined(value) && !isFunction(value) && isValidLength((value as ArrayLike).length); +} + +export function isArrayOf(predicate: (value: unknown) => value is T): (value: unknown) => value is T[] { + return (value: unknown): value is T[] => isArray(value) && value.every(element => predicate(element)); +} + +export function isAsyncFunction(value: unknown): value is ((...arguments_: any[]) => Promise) { + return getObjectType(value) === 'AsyncFunction'; +} + +export function isAsyncGenerator(value: unknown): value is AsyncGenerator { + return isAsyncIterable(value) && isFunction((value as AsyncGenerator).next) && isFunction((value as AsyncGenerator).throw); +} + +export function isAsyncGeneratorFunction(value: unknown): value is ((...arguments_: any[]) => Promise) { + return getObjectType(value) === 'AsyncGeneratorFunction'; +} + +export function isAsyncIterable(value: unknown): value is AsyncIterable { + return isFunction((value as AsyncIterable)?.[Symbol.asyncIterator]); +} + +export function isBigint(value: unknown): value is bigint { + return typeof value === 'bigint'; +} + +export function isBigInt64Array(value: unknown): value is BigInt64Array { + return getObjectType(value) === 'BigInt64Array'; +} + +export function isBigUint64Array(value: unknown): value is BigUint64Array { + return getObjectType(value) === 'BigUint64Array'; +} + +export function isBlob(value: unknown): value is Blob { + return getObjectType(value) === 'Blob'; +} + +export function isBoolean(value: unknown): value is boolean { + return value === true || value === false; +} + +// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type +export function isBoundFunction(value: unknown): value is Function { + return isFunction(value) && !Object.hasOwn(value, 'prototype'); +} + +/** +Note: [Prefer using `Uint8Array` instead of `Buffer`.](https://sindresorhus.com/blog/goodbye-nodejs-buffer) +*/ +export function isBuffer(value: unknown): value is NodeBuffer { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access + return (value as any)?.constructor?.isBuffer?.(value) ?? false; +} + +export function isClass(value: unknown): value is Class { + return isFunction(value) && /^class(?:\s+|\{)/v.test(value.toString()); +} + +export function isDataView(value: unknown): value is DataView { + return getObjectType(value) === 'DataView'; +} + +export function isDate(value: unknown): value is Date { + return getObjectType(value) === 'Date'; +} + +export function isDirectInstanceOf(instance: unknown, class_: Class): instance is T { + if (instance === undefined || instance === null) { + return false; + } + + return Object.getPrototypeOf(instance) === class_.prototype; +} + +export function isEmptyArray(value: unknown): value is never[] { + return isArray(value) && value.length === 0; +} + +export function isEmptyMap(value: unknown): value is Map { + return isMap(value) && value.size === 0; +} + +export function isEmptyObject(value: unknown): value is Record { + return isObject(value) && !isFunction(value) && !isArray(value) && !isMap(value) && !isSet(value) && Object.keys(value).length === 0; +} + +export function isEmptySet(value: unknown): value is Set { + return isSet(value) && value.size === 0; +} + +export function isEmptyString(value: unknown): value is '' { + return isString(value) && value.length === 0; +} + +export function isEmptyStringOrWhitespace(value: unknown): value is '' | Whitespace { + return isEmptyString(value) || isWhitespaceString(value); +} + +export function isEnumCase(value: unknown, targetEnum: T): value is T[keyof T] { + // Numeric enums have reverse mappings (e.g. `Direction[0] = "Up"`), so their runtime object contains both `{ Up: 0 }` and `{ "0": "Up" }`. Filtering out entries that round-trip like a canonical number and point back to an own property leaves only actual enum member values. + const enumObject = targetEnum as Record; + + return Object.entries(enumObject).some(([key, enumValue]) => { + if (!isString(enumValue)) { + return enumValue === value; + } + + const numericKey = Number(key); + if (Number.isNaN(numericKey) || String(numericKey) !== key) { + return enumValue === value; + } + + return enumValue === value && !(Object.hasOwn(enumObject, enumValue) && enumObject[enumValue] === numericKey); + }); +} + +export function isError(value: unknown): value is Error { + // TODO: Use `Error.isError` when targeting Node.js 24. + return getObjectType(value) === 'Error'; +} + +// For numeric guards, preserve branded narrowing for `unknown`, keep the false branch usable for plain `number`, and still narrow mixed unions to `number`. +export function isEvenInteger(value: Input): value is NumericGuardResult; +export function isEvenInteger(value: unknown): boolean { + return isAbsoluteModule2(0)(value); +} + +// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` +export function isFalsy(value: unknown): value is Falsy { + return !value; +} + +export function isFiniteNumber(value: Input): value is NumericGuardResult; +export function isFiniteNumber(value: unknown): boolean { + return Number.isFinite(value); +} + +// TODO: Support detecting Float16Array when targeting Node.js 24. + +export function isFloat32Array(value: unknown): value is Float32Array { + return getObjectType(value) === 'Float32Array'; +} + +export function isFloat64Array(value: unknown): value is Float64Array { + return getObjectType(value) === 'Float64Array'; +} + +export function isFormData(value: unknown): value is FormData { + return getObjectType(value) === 'FormData'; +} + +// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type +export function isFunction(value: unknown): value is Function { + return typeof value === 'function'; +} + +export function isGenerator(value: unknown): value is Generator { + return isIterable(value) && isFunction((value as Generator)?.next) && isFunction((value as Generator)?.throw); +} + +export function isGeneratorFunction(value: unknown): value is GeneratorFunction { + return getObjectType(value) === 'GeneratorFunction'; +} + +const NODE_TYPE_ELEMENT = 1; // eslint-disable-line @typescript-eslint/naming-convention + +const DOM_PROPERTIES_TO_CHECK: Array<(keyof HTMLElement)> = [ // eslint-disable-line @typescript-eslint/naming-convention + 'innerHTML', + 'ownerDocument', + 'style', + 'attributes', + 'nodeValue', +]; + +export function isHtmlElement(value: unknown): value is HTMLElement { + return isObject(value) + && (value as HTMLElement).nodeType === NODE_TYPE_ELEMENT + && isString((value as HTMLElement).nodeName) + && !isPlainObject(value) + && DOM_PROPERTIES_TO_CHECK.every(property => property in value); +} + +export function isInfinite(value: Input): value is NumericGuardResult; +export function isInfinite(value: unknown): boolean { + return value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY; +} + +export function isInRange(value: number, range: number | [number, number]): value is number { + if (isNumber(range)) { + return value >= Math.min(0, range) && value <= Math.max(range, 0); + } + + if (isArray(range) && range.length === 2) { + if (Number.isNaN(range[0]) || Number.isNaN(range[1])) { + throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); + } + + return value >= Math.min(...range) && value <= Math.max(...range); + } + + throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); +} + +export function isInt16Array(value: unknown): value is Int16Array { + return getObjectType(value) === 'Int16Array'; +} + +export function isInt32Array(value: unknown): value is Int32Array { + return getObjectType(value) === 'Int32Array'; +} + +export function isInt8Array(value: unknown): value is Int8Array { + return getObjectType(value) === 'Int8Array'; +} + +export function isInteger(value: Input): value is NumericGuardResult; +export function isInteger(value: unknown): boolean { + return Number.isInteger(value); +} + +export function isIterable(value: unknown): value is Iterable { + return isFunction((value as Iterable)?.[Symbol.iterator]); +} + +export function isMap(value: unknown): value is Map { + return getObjectType(value) === 'Map'; +} + +export function isNan(value: Input): value is NumericGuardResult; +export function isNan(value: unknown): boolean { + return Number.isNaN(value); +} + +export function isNativePromise(value: unknown): value is Promise { + return getObjectType(value) === 'Promise'; +} + +export function isNegativeInteger(value: Input): value is NumericGuardResult; +export function isNegativeInteger(value: unknown): boolean { + return isInteger(value) && value < 0; +} + +export function isNegativeNumber(value: Input): value is NumericGuardResult; +export function isNegativeNumber(value: unknown): boolean { + return isNumber(value) && value < 0; +} + +export function isNodeStream(value: unknown): value is NodeStream { + return isObject(value) && isFunction((value as NodeStream).pipe) && !isObservable(value); +} + +export function isNonEmptyArray(value: T | Item[]): value is [Item, ...Item[]] { + return isArray(value) && value.length > 0; +} + +export function isNonEmptyMap(value: unknown): value is Map { + return isMap(value) && value.size > 0; +} + +// TODO: Use `not` operator here to remove `Map` and `Set` from type guard: +// - https://github.com/Microsoft/TypeScript/pull/29317 +export function isNonEmptyObject(value: unknown): value is Record { + return isObject(value) && !isFunction(value) && !isArray(value) && !isMap(value) && !isSet(value) && Object.keys(value).length > 0; +} + +export function isNonEmptySet(value: unknown): value is Set { + return isSet(value) && value.size > 0; +} + +// TODO: Use `not ''` when the `not` operator is available. +export function isNonEmptyString(value: unknown): value is NonEmptyString { + return isString(value) && value.length > 0; +} + +// TODO: Use `not ''` when the `not` operator is available. +export function isNonEmptyStringAndNotWhitespace(value: unknown): value is NonEmptyString { + return isString(value) && !isEmptyStringOrWhitespace(value); +} + +export function isNonNegativeInteger(value: Input): value is NumericGuardResult; +export function isNonNegativeInteger(value: unknown): boolean { + return isInteger(value) && value >= 0; +} + +export function isNonNegativeNumber(value: Input): value is NumericGuardResult; +export function isNonNegativeNumber(value: unknown): boolean { + return isNumber(value) && value >= 0; +} + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export function isNull(value: unknown): value is null { + return value === null; +} + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export function isNullOrUndefined(value: unknown): value is null | undefined { + return isNull(value) || isUndefined(value); +} + +export function isNumber(value: unknown): value is number { + return typeof value === 'number' && !Number.isNaN(value); +} + +export function isNumericString(value: unknown): value is `${number}` { + return isString(value) && !isEmptyStringOrWhitespace(value) && value === value.trim() && !Number.isNaN(Number(value)); +} + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export function isObject(value: unknown): value is object { + return !isNull(value) && (typeof value === 'object' || isFunction(value)); +} + +export function isObservable(value: unknown): value is ObservableLike { + if (!value) { + return false; + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access + if (Symbol.observable !== undefined && value === (value as any)[Symbol.observable]?.()) { + return true; + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access + if (value === (value as any)['@@observable']?.()) { + return true; + } + + return false; +} + +export function isOddInteger(value: Input): value is NumericGuardResult; +export function isOddInteger(value: unknown): boolean { + return isAbsoluteModule2(1)(value); +} + +export function isOneOf(values: T): (value: unknown) => value is T[number] { + return (value: unknown): value is T[number] => values.includes(value); +} + +export function isPlainObject(value: unknown): value is Record { + // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js + if (typeof value !== 'object' || value === null) { + return false; + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const prototype = Object.getPrototypeOf(value); + + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); +} + +export function isPositiveInteger(value: Input): value is NumericGuardResult; +export function isPositiveInteger(value: unknown): boolean { + return isInteger(value) && value > 0; +} + +export function isPositiveNumber(value: Input): value is NumericGuardResult; +export function isPositiveNumber(value: unknown): boolean { + return isNumber(value) && value > 0; +} + +export function isPrimitive(value: unknown): value is Primitive { + return isNull(value) || isPrimitiveTypeName(typeof value); +} + +export function isPromise(value: unknown): value is Promise { + return isNativePromise(value) || hasPromiseApi(value); +} + +// `PropertyKey` is any value that can be used as an object key (string, number, or symbol). Note: NaN is technically `typeof 'number'` and thus fits TypeScript's `PropertyKey`, but we intentionally exclude it here because using NaN as a property key is almost always a mistake. +export function isPropertyKey(value: unknown): value is PropertyKey { + return isAny([isString, isNumber, isSymbol], value); +} + +export function isRegExp(value: unknown): value is RegExp { + return getObjectType(value) === 'RegExp'; +} + +export function isSafeInteger(value: Input): value is NumericGuardResult; +export function isSafeInteger(value: unknown): boolean { + return Number.isSafeInteger(value); +} + +export function isSet(value: unknown): value is Set { + return getObjectType(value) === 'Set'; +} + +export function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer { + return getObjectType(value) === 'SharedArrayBuffer'; +} + +export function isString(value: unknown): value is string { + return typeof value === 'string'; +} + +export function isSymbol(value: unknown): value is symbol { + return typeof value === 'symbol'; +} + +// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` +// eslint-disable-next-line unicorn/prefer-native-coercion-functions +export function isTruthy(value: T | Falsy): value is T { + return Boolean(value); +} + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +type ResolveTypesOfTypeGuardsTuple = + TypeGuardsOfT extends [TypeGuard, ...infer TOthers] + ? ResolveTypesOfTypeGuardsTuple + : TypeGuardsOfT extends undefined[] + ? ResultOfT + : never; + +export function isTupleLike>>(value: unknown, guards: [...T]): value is ResolveTypesOfTypeGuardsTuple { + if (isArray(guards) && isArray(value) && guards.length === value.length) { + return guards.every((guard, index) => guard(value[index])); + } + + return false; +} + +export function isTypedArray(value: unknown): value is TypedArray { + return isTypedArrayName(getObjectType(value)); +} + +export function isUint16Array(value: unknown): value is Uint16Array { + return getObjectType(value) === 'Uint16Array'; +} + +export function isUint32Array(value: unknown): value is Uint32Array { + return getObjectType(value) === 'Uint32Array'; +} + +export function isUint8Array(value: unknown): value is Uint8Array { + return getObjectType(value) === 'Uint8Array'; +} + +export function isUint8ClampedArray(value: unknown): value is Uint8ClampedArray { + return getObjectType(value) === 'Uint8ClampedArray'; +} + +export function isUndefined(value: unknown): value is undefined { + return value === undefined; +} + +export function isUrlInstance(value: unknown): value is URL { + return getObjectType(value) === 'URL'; +} + +// eslint-disable-next-line unicorn/prevent-abbreviations +export function isUrlSearchParams(value: unknown): value is URLSearchParams { + return getObjectType(value) === 'URLSearchParams'; +} + +export function isUrlString(value: unknown): value is UrlString { + if (!isString(value)) { + return false; + } + + try { + new URL(value); // eslint-disable-line no-new + return true; + } catch { + return false; + } +} + +export function isValidDate(value: unknown): value is Date { + return isDate(value) && !isNan(Number(value)); +} + +export function isValidLength(value: Input): value is NumericGuardResult; +export function isValidLength(value: unknown): boolean { + return isSafeInteger(value) && value >= 0; +} + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export function isWeakMap(value: unknown): value is WeakMap { + return getObjectType(value) === 'WeakMap'; +} + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export function isWeakRef(value: unknown): value is WeakRef { + return getObjectType(value) === 'WeakRef'; +} + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export function isWeakSet(value: unknown): value is WeakSet { + return getObjectType(value) === 'WeakSet'; +} + +export function isWhitespaceString(value: unknown): value is Whitespace { + return isString(value) && /^\s+$/v.test(value); +} + +type ArrayMethod = (function_: (value: unknown, index: number, array: unknown[]) => boolean, thisArgument?: unknown) => boolean; + +function predicateOnArray(method: ArrayMethod, predicate: Predicate, values: unknown[]) { + validatePredicate(predicate); + + if (values.length === 0) { + throw new TypeError('Invalid number of values'); + } + + return method.call(values, predicate); +} + +function typeErrorMessage(description: AssertionTypeDescription, value: unknown): string { + return `Expected value which is \`${description}\`, received value of type \`${is(value)}\`.`; +} + +function typeErrorMessageNot(description: AssertionTypeDescription, value: unknown): string { + return `Expected value which is not \`${description}\`, received value of type \`${is(value)}\`.`; +} + +type NotAssertionResult = Exclude & ([unknown] extends [Value] ? UnknownResult : unknown); + +type NotAssertion = (value: Value, message?: string) => asserts value is NotAssertionResult; + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +type UnknownNotPrimitive = Exclude | object; + +function unique(values: T[]): T[] { + // eslint-disable-next-line unicorn/prefer-spread + return Array.from(new Set(values)); +} + +const andFormatter = new Intl.ListFormat('en', {style: 'long', type: 'conjunction'}); +const orFormatter = new Intl.ListFormat('en', {style: 'long', type: 'disjunction'}); + +function typeErrorMessageMultipleValues(expectedType: AssertionTypeDescription | AssertionTypeDescription[], values: unknown[]): string { + const uniqueExpectedTypes = unique((isArray(expectedType) ? expectedType : [expectedType]).map(value => `\`${value}\``)); + const uniqueValueTypes = unique(values.map(value => `\`${is(value)}\``)); + return `Expected values which are ${orFormatter.format(uniqueExpectedTypes)}. Received values of type${uniqueValueTypes.length > 1 ? 's' : ''} ${andFormatter.format(uniqueValueTypes)}.`; +} + +// Type assertions have to be declared with an explicit type. +// Keep assertion outputs unbranded even when the corresponding `is.*` guard uses a branded subtype. +// The brands exist to preserve useful false-branch narrowing for type guards on `number` inputs, which does not apply to `asserts`. +type Assert = { + // Unknowns. + undefined: (value: unknown, message?: string) => asserts value is undefined; + string: (value: unknown, message?: string) => asserts value is string; + number: (value: unknown, message?: string) => asserts value is number; + finiteNumber: (value: unknown, message?: string) => asserts value is number; + positiveNumber: (value: unknown, message?: string) => asserts value is number; + negativeInteger: (value: unknown, message?: string) => asserts value is number; + negativeNumber: (value: unknown, message?: string) => asserts value is number; + nonNegativeInteger: (value: unknown, message?: string) => asserts value is number; + nonNegativeNumber: (value: unknown, message?: string) => asserts value is number; + positiveInteger: (value: unknown, message?: string) => asserts value is number; + bigint: (value: unknown, message?: string) => asserts value is bigint; + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + function: (value: unknown, message?: string) => asserts value is Function; + // eslint-disable-next-line @typescript-eslint/no-restricted-types + null: (value: unknown, message?: string) => asserts value is null; + class: (value: unknown, message?: string) => asserts value is Class; + boolean: (value: unknown, message?: string) => asserts value is boolean; + symbol: (value: unknown, message?: string) => asserts value is symbol; + numericString: (value: unknown, message?: string) => asserts value is `${number}`; + array: (value: unknown, assertion?: (element: unknown) => asserts element is T, message?: string) => asserts value is T[]; + buffer: (value: unknown, message?: string) => asserts value is NodeBuffer; + blob: (value: unknown, message?: string) => asserts value is Blob; + // eslint-disable-next-line @typescript-eslint/no-restricted-types + nullOrUndefined: (value: unknown, message?: string) => asserts value is null | undefined; + object: (value: unknown, message?: string) => asserts value is Record; + iterable: (value: unknown, message?: string) => asserts value is Iterable; + asyncIterable: (value: unknown, message?: string) => asserts value is AsyncIterable; + generator: (value: unknown, message?: string) => asserts value is Generator; + asyncGenerator: (value: unknown, message?: string) => asserts value is AsyncGenerator; + nativePromise: (value: unknown, message?: string) => asserts value is Promise; + promise: (value: unknown, message?: string) => asserts value is Promise; + generatorFunction: (value: unknown, message?: string) => asserts value is GeneratorFunction; + asyncGeneratorFunction: (value: unknown, message?: string) => asserts value is AsyncGeneratorFunction; + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + asyncFunction: (value: unknown, message?: string) => asserts value is Function; + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + boundFunction: (value: unknown, message?: string) => asserts value is Function; + regExp: (value: unknown, message?: string) => asserts value is RegExp; + date: (value: unknown, message?: string) => asserts value is Date; + error: (value: unknown, message?: string) => asserts value is Error; + map: (value: unknown, message?: string) => asserts value is Map; + set: (value: unknown, message?: string) => asserts value is Set; + // eslint-disable-next-line @typescript-eslint/no-restricted-types + weakMap: (value: unknown, message?: string) => asserts value is WeakMap; + // eslint-disable-next-line @typescript-eslint/no-restricted-types + weakSet: (value: unknown, message?: string) => asserts value is WeakSet; + // eslint-disable-next-line @typescript-eslint/no-restricted-types + weakRef: (value: unknown, message?: string) => asserts value is WeakRef; + int8Array: (value: unknown, message?: string) => asserts value is Int8Array; + uint8Array: (value: unknown, message?: string) => asserts value is Uint8Array; + uint8ClampedArray: (value: unknown, message?: string) => asserts value is Uint8ClampedArray; + int16Array: (value: unknown, message?: string) => asserts value is Int16Array; + uint16Array: (value: unknown, message?: string) => asserts value is Uint16Array; + int32Array: (value: unknown, message?: string) => asserts value is Int32Array; + uint32Array: (value: unknown, message?: string) => asserts value is Uint32Array; + float32Array: (value: unknown, message?: string) => asserts value is Float32Array; + float64Array: (value: unknown, message?: string) => asserts value is Float64Array; + bigInt64Array: (value: unknown, message?: string) => asserts value is BigInt64Array; + bigUint64Array: (value: unknown, message?: string) => asserts value is BigUint64Array; + arrayBuffer: (value: unknown, message?: string) => asserts value is ArrayBuffer; + sharedArrayBuffer: (value: unknown, message?: string) => asserts value is SharedArrayBuffer; + dataView: (value: unknown, message?: string) => asserts value is DataView; + enumCase: (value: unknown, targetEnum: T, message?: string) => asserts value is T[keyof T]; + urlInstance: (value: unknown, message?: string) => asserts value is URL; + urlString: (value: unknown, message?: string) => asserts value is UrlString; + truthy: (value: T | Falsy, message?: string) => asserts value is T; + falsy: (value: unknown, message?: string) => asserts value is Falsy; + nan: (value: unknown, message?: string) => asserts value is number; + primitive: (value: unknown, message?: string) => asserts value is Primitive; + integer: (value: unknown, message?: string) => asserts value is number; + safeInteger: (value: unknown, message?: string) => asserts value is number; + plainObject: (value: unknown, message?: string) => asserts value is Record; + typedArray: (value: unknown, message?: string) => asserts value is TypedArray; + arrayLike: (value: unknown, message?: string) => asserts value is ArrayLike; + tupleLike: >>(value: unknown, guards: [...T], message?: string) => asserts value is ResolveTypesOfTypeGuardsTuple; + htmlElement: (value: unknown, message?: string) => asserts value is HTMLElement; + observable: (value: unknown, message?: string) => asserts value is ObservableLike; + nodeStream: (value: unknown, message?: string) => asserts value is NodeStream; + infinite: (value: unknown, message?: string) => asserts value is number; + emptyArray: (value: unknown, message?: string) => asserts value is never[]; + nonEmptyArray: (value: T | Item[], message?: string) => asserts value is [Item, ...Item[]]; + emptyString: (value: unknown, message?: string) => asserts value is ''; + emptyStringOrWhitespace: (value: unknown, message?: string) => asserts value is '' | Whitespace; + nonEmptyString: (value: unknown, message?: string) => asserts value is string; + nonEmptyStringAndNotWhitespace: (value: unknown, message?: string) => asserts value is string; + emptyObject: (value: unknown, message?: string) => asserts value is Record; + nonEmptyObject: (value: unknown, message?: string) => asserts value is Record; + emptySet: (value: unknown, message?: string) => asserts value is Set; + nonEmptySet: (value: unknown, message?: string) => asserts value is Set; + emptyMap: (value: unknown, message?: string) => asserts value is Map; + nonEmptyMap: (value: unknown, message?: string) => asserts value is Map; + propertyKey: (value: unknown, message?: string) => asserts value is PropertyKey; + formData: (value: unknown, message?: string) => asserts value is FormData; + urlSearchParams: (value: unknown, message?: string) => asserts value is URLSearchParams; + validDate: (value: unknown, message?: string) => asserts value is Date; + validLength: (value: unknown, message?: string) => asserts value is number; + whitespaceString: (value: unknown, message?: string) => asserts value is string; + + // Numbers. + evenInteger: (value: number, message?: string) => asserts value is number; + oddInteger: (value: number, message?: string) => asserts value is number; + + // Two arguments. + directInstanceOf: (instance: unknown, class_: Class, message?: string) => asserts instance is T; + inRange: (value: number, range: number | [number, number], message?: string) => asserts value is number; + + not: NotAssert; + + // Variadic functions. + any: (predicate: Predicate | readonly Predicate[], ...values: unknown[]) => void | never; + all: (predicate: Predicate | readonly Predicate[], ...values: unknown[]) => void | never; + + /** + Asserts that `value` is `undefined` or satisfies the provided `assertion`. + + Useful for optional inputs. + */ + optional: (value: unknown, assertion: (value: unknown, message?: string) => asserts value is T, message?: string) => asserts value is T | undefined; +}; + +type NotAssert = { + undefined: NotAssertion>; + // eslint-disable-next-line @typescript-eslint/no-restricted-types + null: NotAssertion>; + // eslint-disable-next-line @typescript-eslint/no-restricted-types + nullOrUndefined: NotAssertion>; + string: NotAssertion>; + boolean: NotAssertion>; + symbol: NotAssertion>; + bigint: NotAssertion>; + // eslint-disable-next-line @typescript-eslint/no-restricted-types + primitive: NotAssertion; +}; + +// Negative assertions are limited to types where the assertion rejects every TypeScript value assignable to the forbidden type. Structural object types such as `Map`, `Set`, `Date`, and `Array` are excluded because TypeScript accepts shape-compatible mocks while the runtime checks use object brands, so `Exclude` would narrow values that can pass the negative assertion. +function createAssertNot(predicate: Predicate, description: AssertionTypeDescription): NotAssertion { + return (value: Value, message?: string): asserts value is NotAssertionResult => { + if (predicate(value)) { + throw new TypeError(message ?? typeErrorMessageNot(description, value)); + } + }; +} + +export const assertNotUndefined: NotAssertion> = createAssertNot>(isUndefined, 'undefined'); +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export const assertNotNull: NotAssertion> = createAssertNot>(isNull, 'null'); +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export const assertNotNullOrUndefined: NotAssertion> + // eslint-disable-next-line @typescript-eslint/no-restricted-types + = createAssertNot>(isNullOrUndefined, 'null or undefined'); +export const assertNotString: NotAssertion> = createAssertNot>(isString, 'string'); +export const assertNotBoolean: NotAssertion> = createAssertNot>(isBoolean, 'boolean'); +export const assertNotSymbol: NotAssertion> = createAssertNot>(isSymbol, 'symbol'); +export const assertNotBigint: NotAssertion> = createAssertNot>(isBigint, 'bigint'); +export const assertNotPrimitive: NotAssertion = createAssertNot(isPrimitive, 'primitive'); // eslint-disable-line @typescript-eslint/no-restricted-types + +// We intentionally do not support `assert.not(is.undefined, value)`. TypeScript cannot derive safe complement types from arbitrary predicates, and many predicates here are refinements (for example, `is.number` rejects `NaN`). Explicit methods keep runtime checks and type narrowing aligned. +const notAssertions: NotAssert = { + bigint: assertNotBigint, + boolean: assertNotBoolean, + null: assertNotNull, + nullOrUndefined: assertNotNullOrUndefined, + primitive: assertNotPrimitive, + string: assertNotString, + symbol: assertNotSymbol, + undefined: assertNotUndefined, +}; + +export const assert: Assert = { + all: assertAll, + any: assertAny, + not: notAssertions, + optional: assertOptional, + array: assertArray, + arrayBuffer: assertArrayBuffer, + arrayLike: assertArrayLike, + asyncFunction: assertAsyncFunction, + asyncGenerator: assertAsyncGenerator, + asyncGeneratorFunction: assertAsyncGeneratorFunction, + asyncIterable: assertAsyncIterable, + bigint: assertBigint, + bigInt64Array: assertBigInt64Array, + bigUint64Array: assertBigUint64Array, + blob: assertBlob, + boolean: assertBoolean, + boundFunction: assertBoundFunction, + buffer: assertBuffer, + class: assertClass, + dataView: assertDataView, + date: assertDate, + directInstanceOf: assertDirectInstanceOf, + emptyArray: assertEmptyArray, + emptyMap: assertEmptyMap, + emptyObject: assertEmptyObject, + emptySet: assertEmptySet, + emptyString: assertEmptyString, + emptyStringOrWhitespace: assertEmptyStringOrWhitespace, + enumCase: assertEnumCase, + error: assertError, + evenInteger: assertEvenInteger, + falsy: assertFalsy, + finiteNumber: assertFiniteNumber, + float32Array: assertFloat32Array, + float64Array: assertFloat64Array, + formData: assertFormData, + function: assertFunction, + generator: assertGenerator, + generatorFunction: assertGeneratorFunction, + htmlElement: assertHtmlElement, + infinite: assertInfinite, + inRange: assertInRange, + int16Array: assertInt16Array, + int32Array: assertInt32Array, + int8Array: assertInt8Array, + integer: assertInteger, + iterable: assertIterable, + map: assertMap, + nan: assertNan, + nativePromise: assertNativePromise, + negativeInteger: assertNegativeInteger, + negativeNumber: assertNegativeNumber, + nodeStream: assertNodeStream, + nonEmptyArray: assertNonEmptyArray, + nonEmptyMap: assertNonEmptyMap, + nonEmptyObject: assertNonEmptyObject, + nonEmptySet: assertNonEmptySet, + nonEmptyString: assertNonEmptyString, + nonEmptyStringAndNotWhitespace: assertNonEmptyStringAndNotWhitespace, + nonNegativeInteger: assertNonNegativeInteger, + nonNegativeNumber: assertNonNegativeNumber, + null: assertNull, + nullOrUndefined: assertNullOrUndefined, + number: assertNumber, + numericString: assertNumericString, + object: assertObject, + observable: assertObservable, + oddInteger: assertOddInteger, + plainObject: assertPlainObject, + positiveInteger: assertPositiveInteger, + positiveNumber: assertPositiveNumber, + primitive: assertPrimitive, + promise: assertPromise, + propertyKey: assertPropertyKey, + regExp: assertRegExp, + safeInteger: assertSafeInteger, + set: assertSet, + sharedArrayBuffer: assertSharedArrayBuffer, + string: assertString, + symbol: assertSymbol, + truthy: assertTruthy, + tupleLike: assertTupleLike, + typedArray: assertTypedArray, + uint16Array: assertUint16Array, + uint32Array: assertUint32Array, + uint8Array: assertUint8Array, + uint8ClampedArray: assertUint8ClampedArray, + undefined: assertUndefined, + urlInstance: assertUrlInstance, + urlSearchParams: assertUrlSearchParams, + urlString: assertUrlString, + validDate: assertValidDate, + validLength: assertValidLength, + weakMap: assertWeakMap, + weakRef: assertWeakRef, + weakSet: assertWeakSet, + whitespaceString: assertWhitespaceString, +}; + +const methodTypeMap = { + isArray: 'Array', + isArrayBuffer: 'ArrayBuffer', + isArrayLike: 'array-like', + isAsyncFunction: 'AsyncFunction', + isAsyncGenerator: 'AsyncGenerator', + isAsyncGeneratorFunction: 'AsyncGeneratorFunction', + isAsyncIterable: 'AsyncIterable', + isBigint: 'bigint', + isBigInt64Array: 'BigInt64Array', + isBigUint64Array: 'BigUint64Array', + isBlob: 'Blob', + isBoolean: 'boolean', + isBoundFunction: 'bound Function', + isBuffer: 'Buffer', + isClass: 'Class', + isDataView: 'DataView', + isDate: 'Date', + isDirectInstanceOf: 'T', + isEmptyArray: 'empty array', + isEmptyMap: 'empty map', + isEmptyObject: 'empty object', + isEmptySet: 'empty set', + isEmptyString: 'empty string', + isEmptyStringOrWhitespace: 'empty string or whitespace', + isEnumCase: 'EnumCase', + isError: 'Error', + isEvenInteger: 'even integer', + isFalsy: 'falsy', + isFiniteNumber: 'finite number', + isFloat32Array: 'Float32Array', + isFloat64Array: 'Float64Array', + isFormData: 'FormData', + isFunction: 'Function', + isGenerator: 'Generator', + isGeneratorFunction: 'GeneratorFunction', + isHtmlElement: 'HTMLElement', + isInfinite: 'infinite number', + isInRange: 'in range', + isInt16Array: 'Int16Array', + isInt32Array: 'Int32Array', + isInt8Array: 'Int8Array', + isInteger: 'integer', + isIterable: 'Iterable', + isMap: 'Map', + isNan: 'NaN', + isNativePromise: 'native Promise', + isNegativeInteger: 'negative integer', + isNegativeNumber: 'negative number', + isNodeStream: 'Node.js Stream', + isNonEmptyArray: 'non-empty array', + isNonEmptyMap: 'non-empty map', + isNonEmptyObject: 'non-empty object', + isNonEmptySet: 'non-empty set', + isNonEmptyString: 'non-empty string', + isNonEmptyStringAndNotWhitespace: 'non-empty string and not whitespace', + isNonNegativeInteger: 'non-negative integer', + isNonNegativeNumber: 'non-negative number', + isNull: 'null', + isNullOrUndefined: 'null or undefined', + isNumber: 'number', + isNumericString: 'string with a number', + isObject: 'Object', + isObservable: 'Observable', + isOddInteger: 'odd integer', + isPlainObject: 'plain object', + isPositiveInteger: 'positive integer', + isPositiveNumber: 'positive number', + isPrimitive: 'primitive', + isPromise: 'Promise', + isPropertyKey: 'PropertyKey', + isRegExp: 'RegExp', + isSafeInteger: 'safe integer', + isSet: 'Set', + isSharedArrayBuffer: 'SharedArrayBuffer', + isString: 'string', + isSymbol: 'symbol', + isTruthy: 'truthy', + isTupleLike: 'tuple-like', + isTypedArray: 'TypedArray', + isUint16Array: 'Uint16Array', + isUint32Array: 'Uint32Array', + isUint8Array: 'Uint8Array', + isUint8ClampedArray: 'Uint8ClampedArray', + isUndefined: 'undefined', + isUrlInstance: 'URL', + isUrlSearchParams: 'URLSearchParams', + isUrlString: 'string with a URL', + isValidDate: 'valid Date', + isValidLength: 'valid length', + isWeakMap: 'WeakMap', + isWeakRef: 'WeakRef', + isWeakSet: 'WeakSet', + isWhitespaceString: 'whitespace string', +} as const; + +type IsMethodName = keyof typeof methodTypeMap; +const isMethodNames: IsMethodName[] = keysOf(methodTypeMap); + +function isIsMethodName(value: unknown): value is IsMethodName { + return isMethodNames.includes(value as IsMethodName); +} + +export function assertAll(predicate: Predicate | readonly Predicate[], ...values: unknown[]): void | never { + if (values.length === 0) { + throw new TypeError('Invalid number of values'); + } + + if (!isAll(predicate, ...values)) { + const predicateFunction = predicate as Predicate; + const expectedType = !Array.isArray(predicate) && isIsMethodName(predicateFunction.name) ? methodTypeMap[predicateFunction.name] : 'predicate returns truthy for all values'; + throw new TypeError(typeErrorMessageMultipleValues(expectedType, values)); + } +} + +export function assertAny(predicate: Predicate | readonly Predicate[], ...values: unknown[]): void | never { + if (values.length === 0) { + throw new TypeError('Invalid number of values'); + } + + if (!isAny(predicate, ...values)) { + const predicates = Array.isArray(predicate) ? predicate as readonly Predicate[] : [predicate as Predicate]; + const expectedTypes = predicates.map(singlePredicate => isIsMethodName(singlePredicate.name) ? methodTypeMap[singlePredicate.name] : 'predicate returns truthy for any value'); + throw new TypeError(typeErrorMessageMultipleValues(expectedTypes, values)); + } +} + +export function assertOptional(value: unknown, assertion: (value: unknown, message?: string) => asserts value is T, message?: string): asserts value is T | undefined { + if (!isUndefined(value)) { + assertion(value, message); + } +} + +export function assertArray(value: unknown, assertion?: (element: unknown, message?: string) => asserts element is T, message?: string): asserts value is T[] { + if (!isArray(value)) { + throw new TypeError(message ?? typeErrorMessage('Array', value)); + } + + if (assertion) { + for (const element of value) { + // @ts-expect-error: "Assertions require every name in the call target to be declared with an explicit type annotation." + assertion(element, message); + } + } +} + +export function assertArrayBuffer(value: unknown, message?: string): asserts value is ArrayBuffer { + if (!isArrayBuffer(value)) { + throw new TypeError(message ?? typeErrorMessage('ArrayBuffer', value)); + } +} + +export function assertArrayLike(value: unknown, message?: string): asserts value is ArrayLike { + if (!isArrayLike(value)) { + throw new TypeError(message ?? typeErrorMessage('array-like', value)); + } +} + +// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type +export function assertAsyncFunction(value: unknown, message?: string): asserts value is Function { + if (!isAsyncFunction(value)) { + throw new TypeError(message ?? typeErrorMessage('AsyncFunction', value)); + } +} + +export function assertAsyncGenerator(value: unknown, message?: string): asserts value is AsyncGenerator { + if (!isAsyncGenerator(value)) { + throw new TypeError(message ?? typeErrorMessage('AsyncGenerator', value)); + } +} + +export function assertAsyncGeneratorFunction(value: unknown, message?: string): asserts value is AsyncGeneratorFunction { + if (!isAsyncGeneratorFunction(value)) { + throw new TypeError(message ?? typeErrorMessage('AsyncGeneratorFunction', value)); + } +} + +export function assertAsyncIterable(value: unknown, message?: string): asserts value is AsyncIterable { + if (!isAsyncIterable(value)) { + throw new TypeError(message ?? typeErrorMessage('AsyncIterable', value)); + } +} + +export function assertBigint(value: unknown, message?: string): asserts value is bigint { + if (!isBigint(value)) { + throw new TypeError(message ?? typeErrorMessage('bigint', value)); + } +} + +export function assertBigInt64Array(value: unknown, message?: string): asserts value is BigInt64Array { + if (!isBigInt64Array(value)) { + throw new TypeError(message ?? typeErrorMessage('BigInt64Array', value)); + } +} + +export function assertBigUint64Array(value: unknown, message?: string): asserts value is BigUint64Array { + if (!isBigUint64Array(value)) { + throw new TypeError(message ?? typeErrorMessage('BigUint64Array', value)); + } +} + +export function assertBlob(value: unknown, message?: string): asserts value is Blob { + if (!isBlob(value)) { + throw new TypeError(message ?? typeErrorMessage('Blob', value)); + } +} + +export function assertBoolean(value: unknown, message?: string): asserts value is boolean { + if (!isBoolean(value)) { + throw new TypeError(message ?? typeErrorMessage('boolean', value)); + } +} + +// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type +export function assertBoundFunction(value: unknown, message?: string): asserts value is Function { + if (!isBoundFunction(value)) { + throw new TypeError(message ?? typeErrorMessage('bound Function', value)); + } +} + +/** +Note: [Prefer using `Uint8Array` instead of `Buffer`.](https://sindresorhus.com/blog/goodbye-nodejs-buffer) +*/ +export function assertBuffer(value: unknown, message?: string): asserts value is NodeBuffer { + if (!isBuffer(value)) { + throw new TypeError(message ?? typeErrorMessage('Buffer', value)); + } +} + +export function assertClass(value: unknown, message?: string): asserts value is Class { + if (!isClass(value)) { + throw new TypeError(message ?? typeErrorMessage('Class', value)); + } +} + +export function assertDataView(value: unknown, message?: string): asserts value is DataView { + if (!isDataView(value)) { + throw new TypeError(message ?? typeErrorMessage('DataView', value)); + } +} + +export function assertDate(value: unknown, message?: string): asserts value is Date { + if (!isDate(value)) { + throw new TypeError(message ?? typeErrorMessage('Date', value)); + } +} + +export function assertDirectInstanceOf(instance: unknown, class_: Class, message?: string): asserts instance is T { + if (!isDirectInstanceOf(instance, class_)) { + throw new TypeError(message ?? typeErrorMessage('T', instance)); + } +} + +export function assertEmptyArray(value: unknown, message?: string): asserts value is never[] { + if (!isEmptyArray(value)) { + throw new TypeError(message ?? typeErrorMessage('empty array', value)); + } +} + +export function assertEmptyMap(value: unknown, message?: string): asserts value is Map { + if (!isEmptyMap(value)) { + throw new TypeError(message ?? typeErrorMessage('empty map', value)); + } +} + +export function assertEmptyObject(value: unknown, message?: string): asserts value is Record { + if (!isEmptyObject(value)) { + throw new TypeError(message ?? typeErrorMessage('empty object', value)); + } +} + +export function assertEmptySet(value: unknown, message?: string): asserts value is Set { + if (!isEmptySet(value)) { + throw new TypeError(message ?? typeErrorMessage('empty set', value)); + } +} + +export function assertEmptyString(value: unknown, message?: string): asserts value is '' { + if (!isEmptyString(value)) { + throw new TypeError(message ?? typeErrorMessage('empty string', value)); + } +} + +export function assertEmptyStringOrWhitespace(value: unknown, message?: string): asserts value is '' | Whitespace { + if (!isEmptyStringOrWhitespace(value)) { + throw new TypeError(message ?? typeErrorMessage('empty string or whitespace', value)); + } +} + +export function assertEnumCase(value: unknown, targetEnum: T, message?: string): asserts value is T[keyof T] { + if (!isEnumCase(value, targetEnum)) { + throw new TypeError(message ?? typeErrorMessage('EnumCase', value)); + } +} + +export function assertError(value: unknown, message?: string): asserts value is Error { + if (!isError(value)) { + throw new TypeError(message ?? typeErrorMessage('Error', value)); + } +} + +export function assertEvenInteger(value: number, message?: string): asserts value is number { + if (!isEvenInteger(value)) { + throw new TypeError(message ?? typeErrorMessage('even integer', value)); + } +} + +export function assertFalsy(value: unknown, message?: string): asserts value is Falsy { + if (!isFalsy(value)) { + throw new TypeError(message ?? typeErrorMessage('falsy', value)); + } +} + +export function assertFiniteNumber(value: unknown, message?: string): asserts value is number { + if (!isFiniteNumber(value)) { + throw new TypeError(message ?? typeErrorMessage('finite number', value)); + } +} + +export function assertFloat32Array(value: unknown, message?: string): asserts value is Float32Array { + if (!isFloat32Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Float32Array', value)); + } +} + +export function assertFloat64Array(value: unknown, message?: string): asserts value is Float64Array { + if (!isFloat64Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Float64Array', value)); + } +} + +export function assertFormData(value: unknown, message?: string): asserts value is FormData { + if (!isFormData(value)) { + throw new TypeError(message ?? typeErrorMessage('FormData', value)); + } +} + +// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type +export function assertFunction(value: unknown, message?: string): asserts value is Function { + if (!isFunction(value)) { + throw new TypeError(message ?? typeErrorMessage('Function', value)); + } +} + +export function assertGenerator(value: unknown, message?: string): asserts value is Generator { + if (!isGenerator(value)) { + throw new TypeError(message ?? typeErrorMessage('Generator', value)); + } +} + +export function assertGeneratorFunction(value: unknown, message?: string): asserts value is GeneratorFunction { + if (!isGeneratorFunction(value)) { + throw new TypeError(message ?? typeErrorMessage('GeneratorFunction', value)); + } +} + +export function assertHtmlElement(value: unknown, message?: string): asserts value is HTMLElement { + if (!isHtmlElement(value)) { + throw new TypeError(message ?? typeErrorMessage('HTMLElement', value)); + } +} + +export function assertInfinite(value: unknown, message?: string): asserts value is number { + if (!isInfinite(value)) { + throw new TypeError(message ?? typeErrorMessage('infinite number', value)); + } +} + +export function assertInRange(value: number, range: number | [number, number], message?: string): asserts value is number { + if (!isInRange(value, range)) { + throw new TypeError(message ?? typeErrorMessage('in range', value)); + } +} + +export function assertInt16Array(value: unknown, message?: string): asserts value is Int16Array { + if (!isInt16Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Int16Array', value)); + } +} + +export function assertInt32Array(value: unknown, message?: string): asserts value is Int32Array { + if (!isInt32Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Int32Array', value)); + } +} + +export function assertInt8Array(value: unknown, message?: string): asserts value is Int8Array { + if (!isInt8Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Int8Array', value)); + } +} + +export function assertInteger(value: unknown, message?: string): asserts value is number { + if (!isInteger(value)) { + throw new TypeError(message ?? typeErrorMessage('integer', value)); + } +} + +export function assertIterable(value: unknown, message?: string): asserts value is Iterable { + if (!isIterable(value)) { + throw new TypeError(message ?? typeErrorMessage('Iterable', value)); + } +} + +export function assertMap(value: unknown, message?: string): asserts value is Map { + if (!isMap(value)) { + throw new TypeError(message ?? typeErrorMessage('Map', value)); + } +} + +export function assertNan(value: unknown, message?: string): asserts value is number { + if (!isNan(value)) { + throw new TypeError(message ?? typeErrorMessage('NaN', value)); + } +} + +export function assertNativePromise(value: unknown, message?: string): asserts value is Promise { + if (!isNativePromise(value)) { + throw new TypeError(message ?? typeErrorMessage('native Promise', value)); + } +} + +export function assertNegativeInteger(value: unknown, message?: string): asserts value is number { + if (!isNegativeInteger(value)) { + throw new TypeError(message ?? typeErrorMessage('negative integer', value)); + } +} + +export function assertNegativeNumber(value: unknown, message?: string): asserts value is number { + if (!isNegativeNumber(value)) { + throw new TypeError(message ?? typeErrorMessage('negative number', value)); + } +} + +export function assertNodeStream(value: unknown, message?: string): asserts value is NodeStream { + if (!isNodeStream(value)) { + throw new TypeError(message ?? typeErrorMessage('Node.js Stream', value)); + } +} + +export function assertNonEmptyArray(value: T | Item[], message?: string): asserts value is [Item, ...Item[]] { + if (!isNonEmptyArray(value)) { + throw new TypeError(message ?? typeErrorMessage('non-empty array', value)); + } +} + +export function assertNonEmptyMap(value: unknown, message?: string): asserts value is Map { + if (!isNonEmptyMap(value)) { + throw new TypeError(message ?? typeErrorMessage('non-empty map', value)); + } +} + +export function assertNonEmptyObject(value: unknown, message?: string): asserts value is Record { + if (!isNonEmptyObject(value)) { + throw new TypeError(message ?? typeErrorMessage('non-empty object', value)); + } +} + +export function assertNonEmptySet(value: unknown, message?: string): asserts value is Set { + if (!isNonEmptySet(value)) { + throw new TypeError(message ?? typeErrorMessage('non-empty set', value)); + } +} + +export function assertNonEmptyString(value: unknown, message?: string): asserts value is string { + if (!isNonEmptyString(value)) { + throw new TypeError(message ?? typeErrorMessage('non-empty string', value)); + } +} + +export function assertNonEmptyStringAndNotWhitespace(value: unknown, message?: string): asserts value is string { + if (!isNonEmptyStringAndNotWhitespace(value)) { + throw new TypeError(message ?? typeErrorMessage('non-empty string and not whitespace', value)); + } +} + +export function assertNonNegativeInteger(value: unknown, message?: string): asserts value is number { + if (!isNonNegativeInteger(value)) { + throw new TypeError(message ?? typeErrorMessage('non-negative integer', value)); + } +} + +export function assertNonNegativeNumber(value: unknown, message?: string): asserts value is number { + if (!isNonNegativeNumber(value)) { + throw new TypeError(message ?? typeErrorMessage('non-negative number', value)); + } +} + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export function assertNull(value: unknown, message?: string): asserts value is null { + if (!isNull(value)) { + throw new TypeError(message ?? typeErrorMessage('null', value)); + } +} + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export function assertNullOrUndefined(value: unknown, message?: string): asserts value is null | undefined { + if (!isNullOrUndefined(value)) { + throw new TypeError(message ?? typeErrorMessage('null or undefined', value)); + } +} + +export function assertNumber(value: unknown, message?: string): asserts value is number { + if (!isNumber(value)) { + throw new TypeError(message ?? typeErrorMessage('number', value)); + } +} + +export function assertNumericString(value: unknown, message?: string): asserts value is `${number}` { + if (!isNumericString(value)) { + throw new TypeError(message ?? typeErrorMessage('string with a number', value)); + } +} + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export function assertObject(value: unknown, message?: string): asserts value is object { + if (!isObject(value)) { + throw new TypeError(message ?? typeErrorMessage('Object', value)); + } +} + +export function assertObservable(value: unknown, message?: string): asserts value is ObservableLike { + if (!isObservable(value)) { + throw new TypeError(message ?? typeErrorMessage('Observable', value)); + } +} + +export function assertOddInteger(value: number, message?: string): asserts value is number { + if (!isOddInteger(value)) { + throw new TypeError(message ?? typeErrorMessage('odd integer', value)); + } +} + +export function assertPlainObject(value: unknown, message?: string): asserts value is Record { + if (!isPlainObject(value)) { + throw new TypeError(message ?? typeErrorMessage('plain object', value)); + } +} + +export function assertPositiveInteger(value: unknown, message?: string): asserts value is number { + if (!isPositiveInteger(value)) { + throw new TypeError(message ?? typeErrorMessage('positive integer', value)); + } +} + +export function assertPositiveNumber(value: unknown, message?: string): asserts value is number { + if (!isPositiveNumber(value)) { + throw new TypeError(message ?? typeErrorMessage('positive number', value)); + } +} + +export function assertPrimitive(value: unknown, message?: string): asserts value is Primitive { + if (!isPrimitive(value)) { + throw new TypeError(message ?? typeErrorMessage('primitive', value)); + } +} + +export function assertPromise(value: unknown, message?: string): asserts value is Promise { + if (!isPromise(value)) { + throw new TypeError(message ?? typeErrorMessage('Promise', value)); + } +} + +export function assertPropertyKey(value: unknown, message?: string): asserts value is PropertyKey { + if (!isPropertyKey(value)) { + throw new TypeError(message ?? typeErrorMessage('PropertyKey', value)); + } +} + +export function assertRegExp(value: unknown, message?: string): asserts value is RegExp { + if (!isRegExp(value)) { + throw new TypeError(message ?? typeErrorMessage('RegExp', value)); + } +} + +export function assertSafeInteger(value: unknown, message?: string): asserts value is number { + if (!isSafeInteger(value)) { + throw new TypeError(message ?? typeErrorMessage('safe integer', value)); + } +} + +export function assertSet(value: unknown, message?: string): asserts value is Set { + if (!isSet(value)) { + throw new TypeError(message ?? typeErrorMessage('Set', value)); + } +} + +export function assertSharedArrayBuffer(value: unknown, message?: string): asserts value is SharedArrayBuffer { + if (!isSharedArrayBuffer(value)) { + throw new TypeError(message ?? typeErrorMessage('SharedArrayBuffer', value)); + } +} + +export function assertString(value: unknown, message?: string): asserts value is string { + if (!isString(value)) { + throw new TypeError(message ?? typeErrorMessage('string', value)); + } +} + +export function assertSymbol(value: unknown, message?: string): asserts value is symbol { + if (!isSymbol(value)) { + throw new TypeError(message ?? typeErrorMessage('symbol', value)); + } +} + +export function assertTruthy(value: T | Falsy, message?: string): asserts value is T { + if (!isTruthy(value)) { + throw new TypeError(message ?? typeErrorMessage('truthy', value)); + } +} + +export function assertTupleLike>>(value: unknown, guards: [...T], message?: string): asserts value is ResolveTypesOfTypeGuardsTuple { + if (!isTupleLike(value, guards)) { + throw new TypeError(message ?? typeErrorMessage('tuple-like', value)); + } +} + +export function assertTypedArray(value: unknown, message?: string): asserts value is TypedArray { + if (!isTypedArray(value)) { + throw new TypeError(message ?? typeErrorMessage('TypedArray', value)); + } +} + +export function assertUint16Array(value: unknown, message?: string): asserts value is Uint16Array { + if (!isUint16Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Uint16Array', value)); + } +} + +export function assertUint32Array(value: unknown, message?: string): asserts value is Uint32Array { + if (!isUint32Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Uint32Array', value)); + } +} + +export function assertUint8Array(value: unknown, message?: string): asserts value is Uint8Array { + if (!isUint8Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Uint8Array', value)); + } +} + +export function assertUint8ClampedArray(value: unknown, message?: string): asserts value is Uint8ClampedArray { + if (!isUint8ClampedArray(value)) { + throw new TypeError(message ?? typeErrorMessage('Uint8ClampedArray', value)); + } +} + +export function assertUndefined(value: unknown, message?: string): asserts value is undefined { + if (!isUndefined(value)) { + throw new TypeError(message ?? typeErrorMessage('undefined', value)); + } +} + +export function assertUrlInstance(value: unknown, message?: string): asserts value is URL { + if (!isUrlInstance(value)) { + throw new TypeError(message ?? typeErrorMessage('URL', value)); + } +} + +// eslint-disable-next-line unicorn/prevent-abbreviations +export function assertUrlSearchParams(value: unknown, message?: string): asserts value is URLSearchParams { + if (!isUrlSearchParams(value)) { + throw new TypeError(message ?? typeErrorMessage('URLSearchParams', value)); + } +} + +export function assertUrlString(value: unknown, message?: string): asserts value is UrlString { + if (!isUrlString(value)) { + throw new TypeError(message ?? typeErrorMessage('string with a URL', value)); + } +} + +export function assertValidDate(value: unknown, message?: string): asserts value is Date { + if (!isValidDate(value)) { + throw new TypeError(message ?? typeErrorMessage('valid Date', value)); + } +} + +export function assertValidLength(value: unknown, message?: string): asserts value is number { + if (!isValidLength(value)) { + throw new TypeError(message ?? typeErrorMessage('valid length', value)); + } +} + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export function assertWeakMap(value: unknown, message?: string): asserts value is WeakMap { + if (!isWeakMap(value)) { + throw new TypeError(message ?? typeErrorMessage('WeakMap', value)); + } +} + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export function assertWeakRef(value: unknown, message?: string): asserts value is WeakRef { + if (!isWeakRef(value)) { + throw new TypeError(message ?? typeErrorMessage('WeakRef', value)); + } +} + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export function assertWeakSet(value: unknown, message?: string): asserts value is WeakSet { + if (!isWeakSet(value)) { + throw new TypeError(message ?? typeErrorMessage('WeakSet', value)); + } +} + +export function assertWhitespaceString(value: unknown, message?: string): asserts value is string { + if (!isWhitespaceString(value)) { + throw new TypeError(message ?? typeErrorMessage('whitespace string', value)); + } +} + +export default is; + +export type { + ArrayLike, + Class, + EvenInteger, + FiniteNumber, + Integer, + NaN, + NegativeInfinity, + NegativeInteger, + NegativeNumber, + NodeStream, + NonNegativeInteger, + NonNegativeNumber, + ObservableLike, + OddInteger, + PositiveInfinity, + PositiveInteger, + PositiveNumber, + Predicate, + Primitive, + SafeInteger, + TypedArray, + UrlString, + ValidLength, +} from './types.ts'; diff --git a/source/types.ts b/source/types.ts new file mode 100644 index 0000000..9255072 --- /dev/null +++ b/source/types.ts @@ -0,0 +1,199 @@ +// Extracted from https://github.com/sindresorhus/type-fest/blob/78019f42ea888b0cdceb41a4a78163868de57555/index.d.ts + +/** +Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). +*/ +export type Primitive = + // eslint-disable-next-line @typescript-eslint/no-restricted-types + | null + | undefined + | string + | number + | boolean + | symbol + | bigint; + +/** +Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). +*/ +type Constructor = new(...arguments_: Arguments) => T; + +/** +Matches a [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). +*/ +export type Class = Constructor & {prototype: T}; + +/** +Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`. +*/ +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; + +declare global { + // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- This must be an `interface` so it can be merged. + interface SymbolConstructor { + readonly observable: symbol; + } +} + +/** +Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable). +*/ +export type ObservableLike = { + subscribe(observer: (value: unknown) => void): void; + [Symbol.observable](): ObservableLike; +}; + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export type Falsy = false | 0 | 0n | '' | null | undefined; + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +export type WeakRef = { + readonly [Symbol.toStringTag]: 'WeakRef'; + deref(): T | undefined; +}; + +export type ArrayLike = { + readonly [index: number]: T; + readonly length: number; +}; + +export type NodeStream = { + pipe(destination: T, options?: {end?: boolean}): T; +} & NodeJS.EventEmitter; + +export type Predicate = (value: unknown) => boolean; + +export type NonEmptyString = string & {0: string}; + +export type Whitespace = ' '; + +type Brand = Readonly>; + +/** +A string that represents a valid URL. + +This is a branded type to prevent incorrect TypeScript type narrowing. +*/ +export type UrlString = string & {readonly __brand: 'UrlString'}; + +// Keep numeric guards branded and simple. This intentionally favors correct false-branch narrowing for `number` inputs over perfect success-branch narrowing for numeric literal unions. + +/** +The IEEE 754 "Not-a-Number" value, typed as a subtype of `number`. + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type NaN = number & Brand<'__nanBrand'>; + +/** +A finite number (excludes `NaN`, `Infinity`, and `-Infinity`). + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type FiniteNumber = number & Brand<'__finiteNumberBrand'>; + +/** +A number greater than or equal to zero. + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type NonNegativeNumber = number & Brand<'__nonNegativeNumberBrand'>; + +/** +An integer value (no fractional part). + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type Integer = FiniteNumber & Brand<'__integerBrand'>; + +/** +A number greater than zero. + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type PositiveNumber = NonNegativeNumber & Brand<'__positiveNumberBrand'>; + +/** +A number less than zero. + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type NegativeNumber = number & Brand<'__negativeNumberBrand'>; + +/** +An integer less than zero. + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type NegativeInteger = Integer & NegativeNumber & Brand<'__negativeIntegerBrand'>; + +/** +An integer greater than or equal to zero. + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type NonNegativeInteger = Integer & NonNegativeNumber & Brand<'__nonNegativeIntegerBrand'>; + +/** +An integer greater than zero. + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type PositiveInteger = NonNegativeInteger & PositiveNumber & Brand<'__positiveIntegerBrand'>; + +// Note: type-fest uses the `1e999` overflow trick to represent these types (since TypeScript has +// no built-in Infinity type), but we use branded types here for consistency and to avoid +// relying on numeric overflow behavior. + +/** +A positive infinite number (`Infinity`). + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type PositiveInfinity = PositiveNumber & Brand<'__positiveInfinityBrand'>; + +/** +A negative infinite number (`-Infinity`). + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type NegativeInfinity = NegativeNumber & Brand<'__negativeInfinityBrand'>; + +/** +A safe integer (within the range of `Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`). + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type SafeInteger = Integer & Brand<'__safeIntegerBrand'>; + +/** +An even integer. + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type EvenInteger = Integer & Brand<'__evenIntegerBrand'>; + +/** +An odd integer. + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type OddInteger = Integer & Brand<'__oddIntegerBrand'>; + +/** +A non-negative safe integer, suitable as an array or string length. + +Branded to prevent false-branch narrowing to `never` when the input is `number`. +*/ +export type ValidLength = SafeInteger & NonNegativeInteger & Brand<'__validLengthBrand'>; diff --git a/source/utilities.ts b/source/utilities.ts new file mode 100644 index 0000000..686edb1 --- /dev/null +++ b/source/utilities.ts @@ -0,0 +1,3 @@ +export function keysOf>(value: T): Array { + return Object.keys(value) as Array; // eslint-disable-line @typescript-eslint/no-unnecessary-type-assertion +} diff --git a/test.js b/test.js deleted file mode 100644 index 7868637..0000000 --- a/test.js +++ /dev/null @@ -1,295 +0,0 @@ -import util from 'util'; -import test from 'ava'; -import m from '.'; - -const isNode8orHigher = Number(process.versions.node.split('.')[0]) >= 8; - -const PromiseSubclassFixture = class extends Promise {}; -const ErrorSubclassFixture = class extends Error {}; - -const types = new Map([ - ['undefined', undefined], - ['null', null], - ['string', '🦄'], - ['number', [ - 6, - 1.4, - 0, - -0, - Infinity, - -Infinity - ]], - ['boolean', [ - true, - false - ]], - ['symbol', Symbol('🦄')], - ['array', [ - [1, 2], - new Array(2) - ]], - ['function', [ - function foo() {}, // eslint-disable-line func-names - function () {}, - () => {}, - async function () {}, - function * () {} - ]], - ['buffer', Buffer.from('🦄')], - ['object', [ - {x: 1}, - Object.create({x: 1}) - ]], - ['regExp', [ - /\w/, - new RegExp('\\w') - ]], - ['date', new Date()], - ['error', [ - new Error('🦄'), - new ErrorSubclassFixture() - ]], - ['nativePromise', [ - Promise.resolve(), - PromiseSubclassFixture.resolve() - ]], - ['promise', {then() {}, catch() {}}], - ['map', new Map()], - ['set', new Set()], - ['weakMap', new WeakMap()], - ['int8Array', new Int8Array()], - ['uint8Array', new Uint8Array()], - ['uint8ClampedArray', new Uint8ClampedArray()], - ['uint16Array', new Uint16Array()], - ['int32Array', new Int32Array()], - ['uint32Array', new Uint32Array()], - ['float32Array', new Float32Array()], - ['float64Array', new Float64Array()], - ['arrayBuffer', new ArrayBuffer(10)], - ['nan', [ - NaN, - Number.NaN - ]], - ['nullOrUndefined', [ - null, - undefined - ]], - ['plainObject', [ - {x: 1}, - Object.create(null), - new Object() // eslint-disable-line no-new-object - ]], - ['integer', 6] -]); - -// This ensure a certain method matches only the types -// it's supposed to and none of the other methods' types -const testType = (t, type, exclude) => { - for (const [key, value] of types) { - // TODO: Automatically exclude value types in other tests that we have in the current one. - // Could reduce the use of `exclude`. - if (exclude && exclude.indexOf(key) !== -1) { - continue; - } - - const assert = key === type ? t.true.bind(t) : t.false.bind(t); - const is = m[type]; - const fixtures = Array.isArray(value) ? value : [value]; - - for (const fixture of fixtures) { - assert(is(fixture), `Value: ${util.inspect(fixture)}`); - } - } -}; - -test('is.undefined', t => { - testType(t, 'undefined', ['nullOrUndefined']); -}); - -test('is.null', t => { - testType(t, 'null', ['nullOrUndefined']); -}); - -test('is.string', t => { - testType(t, 'string'); -}); - -test('is.number', t => { - testType(t, 'number', ['nan', 'integer']); -}); - -test('is.boolean', t => { - testType(t, 'boolean'); -}); - -test('is.symbol', t => { - testType(t, 'symbol'); -}); - -test('is.array', t => { - testType(t, 'array'); -}); - -test('is.function', t => { - testType(t, 'function'); -}); - -test('is.buffer', t => { - testType(t, 'buffer'); -}); - -test('is.object', t => { - for (const el of types.get('object')) { - t.true(m.object(el)); - } -}); - -test('is.regExp', t => { - testType(t, 'regExp'); -}); - -test('is.date', t => { - testType(t, 'date'); -}); - -test('is.error', t => { - testType(t, 'error'); -}); - -if (isNode8orHigher) { - test('is.nativePromise', t => { - testType(t, 'nativePromise'); - }); - - test('is.promise', t => { - testType(t, 'promise', ['nativePromise']); - }); -} - -test('is.map', t => { - testType(t, 'map'); -}); - -test('is.set', t => { - testType(t, 'set'); -}); - -test('is.weakMap', t => { - testType(t, 'weakMap'); -}); - -test('is.weakSet', t => { - testType(t, 'weakSet'); -}); - -test('is.int8Array', t => { - testType(t, 'int8Array'); -}); - -test('is.uint8Array', t => { - testType(t, 'uint8Array', ['buffer']); -}); - -test('is.uint8ClampedArray', t => { - testType(t, 'uint8ClampedArray'); -}); - -test('is.int16Array', t => { - testType(t, 'int16Array'); -}); - -test('is.uint16Array', t => { - testType(t, 'uint16Array'); -}); - -test('is.int32Array', t => { - testType(t, 'int32Array'); -}); - -test('is.uint32Array', t => { - testType(t, 'uint32Array'); -}); - -test('is.float32Array', t => { - testType(t, 'float32Array'); -}); - -test('is.float64Array', t => { - testType(t, 'float64Array'); -}); - -test('is.arrayBuffer', t => { - testType(t, 'arrayBuffer'); -}); - -test('is.dataView', t => { - testType(t, 'arrayBuffer'); -}); - -test('is.nan', t => { - testType(t, 'nan'); -}); - -test('is.nullOrUndefined', t => { - testType(t, 'nullOrUndefined', ['undefined', 'null']); -}); - -test('is.primitive', t => { - const primitives = [ - undefined, - null, - '🦄', - 6, - Infinity, - -Infinity, - true, - false, - Symbol('🦄') - ]; - - for (const el of primitives) { - t.true(m.primitive(el)); - } -}); - -test('is.integer', t => { - testType(t, 'integer', ['number']); - t.false(m.integer(1.4)); -}); - -test('is.plainObject', t => { - testType(t, 'plainObject', ['object', 'promise']); -}); - -test('is.iterable', t => { - t.true(m.iterable('')); - t.true(m.iterable([])); - t.true(m.iterable(new Map())); - t.false(m.iterable(null)); - t.false(m.iterable(undefined)); - t.false(m.iterable(0)); - t.false(m.iterable(NaN)); - t.false(m.iterable(Infinity)); - t.false(m.iterable({})); -}); - -test('is.typedArray', t => { - const typedArrays = [ - new Int8Array(), - new Uint8Array(), - new Uint8ClampedArray(), - new Uint16Array(), - new Int32Array(), - new Uint32Array(), - new Float32Array(), - new Float64Array() - ]; - - for (const el of typedArrays) { - t.true(m.typedArray(el)); - } - - t.false(m.typedArray(new ArrayBuffer(1))); - t.false(m.typedArray([])); - t.false(m.typedArray({})); -}); diff --git a/test/test.ts b/test/test.ts new file mode 100644 index 0000000..2f98bfb --- /dev/null +++ b/test/test.ts @@ -0,0 +1,2822 @@ +/* eslint-disable @typescript-eslint/no-empty-function, @stylistic/curly-newline, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/prefer-nullish-coalescing, @typescript-eslint/no-unsafe-argument */ +import {Buffer} from 'node:buffer'; +import fs from 'node:fs'; +import net from 'node:net'; +import Stream from 'node:stream'; +import {inspect} from 'node:util'; +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {JSDOM} from 'jsdom'; +import {Subject, Observable} from 'rxjs'; +import {temporaryFile} from 'tempy'; +import {expectTypeOf} from 'expect-type'; +import ZenObservable from 'zen-observable'; +import is, { + assert as isAssert, + assertPropertyKey, + type AssertionTypeDescription, + type NaN as NaNType, + type Predicate, + type Primitive, + type TypedArray, + type TypeName, + type UrlString, +} from '../source/index.ts'; +import {keysOf} from '../source/utilities.ts'; + +class PromiseSubclassFixture extends Promise {} +class ErrorSubclassFixture extends Error {} + +const {window} = new JSDOM(); +const {document} = window; + +type Test = Readonly<{ + fixtures: unknown[]; + typename?: TypeName; + typeDescription?: AssertionTypeDescription; +}>; + +// Every entry should be unique and belongs in the most specific type for that entry +const reusableFixtures = { + asyncFunction: [async function () {}, async () => {}], + asyncGeneratorFunction: [ + async function * () {}, + async function * () { + yield 4; + }, + ], + boundFunction: [() => {}, function () {}.bind(null)], // eslint-disable-line no-extra-bind + buffer: [Buffer.from('🦄')], + emptyArray: [[], new Array()], // eslint-disable-line @typescript-eslint/no-array-constructor + emptyMap: [new Map()], + emptySet: [new Set()], + emptyString: ['', String()], + function: [ + function foo() {}, // eslint-disable-line func-names + function () {}, + ], + generatorFunction: [ + function * () {}, + function * () { + yield 4; + }, + ], + infinite: [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY], + integer: [0, -0, 6], + nativePromise: [Promise.resolve(), PromiseSubclassFixture.resolve()], + number: [1.4], + numericString: ['5', '-3.2', 'Infinity', '0x56'], + plainObject: [ + {x: 1}, + Object.create(null), + new Object(), // eslint-disable-line no-object-constructor + structuredClone({x: 1}), + structuredClone(Object.create(null)), + structuredClone(new Object()), // eslint-disable-line no-object-constructor + ], + promise: [Object.create({then() {}, catch() {}})], // eslint-disable-line unicorn/no-thenable + safeInteger: [(2 ** 53) - 1, -(2 ** 53) + 1], +} as const satisfies Partial<{[K in keyof typeof is]: unknown[]}>; + +const primitiveTypes = { + undefined: { + fixtures: [ + undefined, + ], + typename: 'undefined', + }, + null: { + fixtures: [ + null, + ], + typename: 'null', + }, + string: { + fixtures: [ + '🦄', + 'hello world', + ...reusableFixtures.emptyString, + ...reusableFixtures.numericString, + ], + typename: 'string', + }, + emptyString: { + fixtures: [...reusableFixtures.emptyString], + typename: 'string', + typeDescription: 'empty string', + }, + number: { + fixtures: [ + ...reusableFixtures.number, + ...reusableFixtures.infinite, + ...reusableFixtures.integer, + ...reusableFixtures.safeInteger, + ], + typename: 'number', + }, + bigint: { + fixtures: [ + 1n, + 0n, + -0n, + 1234n, + ], + typename: 'bigint', + }, + boolean: { + fixtures: [ + true, false, + ], + typename: 'boolean', + }, + numericString: { + fixtures: [...reusableFixtures.numericString], + typename: 'string', + typeDescription: 'string with a number', + }, + nan: { + fixtures: [ + NaN, // eslint-disable-line unicorn/prefer-number-properties + Number.NaN, + ], + typename: 'NaN', + typeDescription: 'NaN', + }, + nullOrUndefined: { + fixtures: [ + null, + undefined, + ], + typeDescription: 'null or undefined', + }, + integer: { + fixtures: [...reusableFixtures.integer, ...reusableFixtures.safeInteger], + typename: 'number', + typeDescription: 'integer', + }, + safeInteger: { + fixtures: [...reusableFixtures.integer, ...reusableFixtures.safeInteger], + typename: 'number', + typeDescription: 'safe integer', + }, + infinite: { + fixtures: [...reusableFixtures.infinite], + typename: 'number', + typeDescription: 'infinite number', + }, +} as const satisfies Partial<{[K in keyof typeof is]: Test}>; + +const objectTypes = { + symbol: { + fixtures: [ + Symbol('🦄'), + ], + typename: 'symbol', + }, + array: { + fixtures: [ + [1, 2], + Array.from({length: 2}), + ...reusableFixtures.emptyArray, + ], + typename: 'Array', + }, + emptyArray: { + fixtures: [...reusableFixtures.emptyArray], + typename: 'Array', + typeDescription: 'empty array', + }, + function: { + fixtures: [ + ...reusableFixtures.asyncFunction, + ...reusableFixtures.asyncGeneratorFunction, + ...reusableFixtures.boundFunction, + ...reusableFixtures.function, + ...reusableFixtures.generatorFunction, + ], + typename: 'Function', + }, + buffer: { + fixtures: [...reusableFixtures.buffer], + typename: 'Buffer', + }, + blob: { + fixtures: [ + new window.Blob(), + ], + typename: 'Blob', + }, + object: { + fixtures: [ + Object.create({x: 1}), + {[Symbol.toStringTag]: 'String'}, + ...reusableFixtures.plainObject, + ], + typename: 'Object', + }, + regExp: { + fixtures: [ + /\w/v, + // eslint-disable-next-line prefer-regex-literals + new RegExp(String.raw`\w`, 'v'), + ], + typename: 'RegExp', + }, + date: { + fixtures: [ + new Date(), + ], + typename: 'Date', + }, + error: { + fixtures: [ + new Error('🦄'), + new ErrorSubclassFixture(), + ], + typename: 'Error', + }, + nativePromise: { + fixtures: [...reusableFixtures.nativePromise], + typename: 'Promise', + typeDescription: 'native Promise', + }, + promise: { + fixtures: [ + ...reusableFixtures.nativePromise, + ...reusableFixtures.promise, + ], + typename: 'Promise', + typeDescription: 'Promise', + }, + generator: { + fixtures: [ + (function * () { + yield 4; + })(), + ], + typename: 'Generator', + }, + asyncGenerator: { + fixtures: [ + (async function * () { + yield 4; + })(), + ], + typename: 'AsyncGenerator', + }, + generatorFunction: { + fixtures: [...reusableFixtures.generatorFunction], + typename: 'Function', + typeDescription: 'GeneratorFunction', + }, + asyncGeneratorFunction: { + fixtures: [...reusableFixtures.asyncGeneratorFunction], + typename: 'Function', + typeDescription: 'AsyncGeneratorFunction', + }, + asyncFunction: { + fixtures: [...reusableFixtures.asyncFunction], + typename: 'Function', + typeDescription: 'AsyncFunction', + }, + boundFunction: { + fixtures: [...reusableFixtures.boundFunction, ...reusableFixtures.asyncFunction], + typename: 'Function', + typeDescription: 'bound Function', + }, + map: { + fixtures: [ + new Map([['one', '1']]), + ...reusableFixtures.emptyMap, + ], + typename: 'Map', + }, + emptyMap: { + fixtures: [...reusableFixtures.emptyMap], + typename: 'Map', + typeDescription: 'empty map', + }, + set: { + fixtures: [ + new Set(['one']), + ...reusableFixtures.emptySet, + ], + typename: 'Set', + }, + emptySet: { + fixtures: [...reusableFixtures.emptySet], + typename: 'Set', + typeDescription: 'empty set', + }, + weakSet: { + fixtures: [ + new WeakSet(), + ], + typename: 'WeakSet', + }, + weakRef: { + fixtures: [ + new window.WeakRef({}), + ], + typename: 'WeakRef', + }, + weakMap: { + fixtures: [ + new WeakMap(), + ], + typename: 'WeakMap', + }, + int8Array: { + fixtures: [ + new Int8Array(), + ], + typename: 'Int8Array', + }, + uint8Array: { + fixtures: [ + new Uint8Array(), + ], + typename: 'Uint8Array', + }, + uint8ClampedArray: { + fixtures: [ + new Uint8ClampedArray(), + ], + typename: 'Uint8ClampedArray', + }, + int16Array: { + fixtures: [ + new Int16Array(), + ], + typename: 'Int16Array', + }, + uint16Array: { + fixtures: [ + new Uint16Array(), + ], + typename: 'Uint16Array', + }, + int32Array: { + fixtures: [ + new Int32Array(), + ], + typename: 'Int32Array', + }, + uint32Array: { + fixtures: [ + new Uint32Array(), + ], + typename: 'Uint32Array', + }, + float32Array: { + fixtures: [ + new Float32Array(), + ], + typename: 'Float32Array', + }, + float64Array: { + fixtures: [ + new Float64Array(), + ], + typename: 'Float64Array', + }, + bigInt64Array: { + fixtures: [ + new BigInt64Array(), + ], + typename: 'BigInt64Array', + }, + bigUint64Array: { + fixtures: [ + new BigUint64Array(), + ], + typename: 'BigUint64Array', + }, + arrayBuffer: { + fixtures: [ + new ArrayBuffer(10), + ], + typename: 'ArrayBuffer', + }, + dataView: { + fixtures: [ + new DataView(new ArrayBuffer(10)), + ], + typename: 'DataView', + }, + plainObject: { + fixtures: [ + ...reusableFixtures.plainObject, + ], + typename: 'Object', + typeDescription: 'plain object', + }, + htmlElement: { + fixtures: [ + 'div', + 'input', + 'span', + 'img', + 'canvas', + 'script', + ] + .map(fixture => document.createElement(fixture)), + typeDescription: 'HTMLElement', + }, + observable: { + fixtures: [ + new Observable(), + new Subject(), + new ZenObservable(() => {}), + ], + typename: 'Observable', + }, + nodeStream: { + fixtures: [ + fs.createReadStream('readme.md'), + fs.createWriteStream(temporaryFile()), + new net.Socket(), + new Stream.Duplex(), + new Stream.PassThrough(), + new Stream.Readable(), + new Stream.Transform(), + new Stream.Stream(), + new Stream.Writable(), + ], + typename: 'Object', + typeDescription: 'Node.js Stream', + }, + formData: { + fixtures: [ + new window.FormData(), + ], + typename: 'FormData', + }, +} as const satisfies Partial<{[K in keyof typeof is]: Test}>; + +const types = { + ...objectTypes, + ...primitiveTypes, +} as const satisfies Partial<{[K in keyof typeof is]: Test}>; + +type TypeNameWithFixture = keyof typeof types; + +const subClasses = new Map([ + ['uint8Array', ['buffer']], // It's too hard to differentiate the two + ['object', keysOf(objectTypes)], +]); + +const notAssertionFixtures = { + bigint: {fixture: 1n, nonFixture: '🦄', typeDescription: 'bigint'}, + boolean: {fixture: false, nonFixture: '🦄', typeDescription: 'boolean'}, + null: {fixture: null, nonFixture: '🦄', typeDescription: 'null'}, + nullOrUndefined: {fixtures: [null, undefined], nonFixture: '🦄', typeDescription: 'null or undefined'}, + primitive: {fixtures: [false, null, undefined], nonFixture: [], typeDescription: 'primitive'}, + string: {fixture: '🦄', nonFixture: 1, typeDescription: 'string'}, + symbol: {fixture: Symbol('🦄'), nonFixture: '🦄', typeDescription: 'symbol'}, + undefined: {fixture: undefined, nonFixture: null, typeDescription: 'undefined'}, +} as const satisfies Record; + +// This ensures a certain method matches only the types it's supposed to and none of the other methods' types +for (const type of keysOf(types)) { + test(`is.${type}`, () => { + const {fixtures, typeDescription, typename} = types[type] as Test; + const valueType = typeDescription ?? typename ?? 'unspecified'; + + const testAssert: (value: unknown) => never | void = isAssert[type]; + const testIs: Predicate = is[type]; + + for (const fixture of fixtures) { + assert.ok(testIs(fixture), `Value: ${inspect(fixture)}`); + assert.doesNotThrow(() => { + testAssert(fixture); + }); + + if (typename !== undefined) { + assert.strictEqual(is(fixture), typename); + } + } + + for (const key of keysOf(types).filter(key => key !== type)) { + if (subClasses.has(type) && subClasses.get(type)?.includes(key)) { + continue; + } + + for (let i = 0; i < types[key].fixtures.length; i += 1) { + const fixture: unknown = types[key].fixtures[i]; + + if (fixtures.includes(fixture)) { + continue; + } + + assert.strictEqual(testIs(fixture), false, `${key}.fixture[${i}]: ${inspect(fixture)} should not be ${type}`); + assert.throws(() => { + testAssert(fixture); + }, { + message: `Expected value which is \`${valueType}\`, received value of type \`${is(fixture)}\`.`, + }); + } + } + }); +} + +test('is.positiveNumber', () => { + assert.ok(is.positiveNumber(6)); + assert.ok(is.positiveNumber(1.4)); + assert.ok(is.positiveNumber(Number.POSITIVE_INFINITY)); + + assert.doesNotThrow(() => { + isAssert.positiveNumber(6); + }); + assert.doesNotThrow(() => { + isAssert.positiveNumber(1.4); + }); + assert.doesNotThrow(() => { + isAssert.positiveNumber(Number.POSITIVE_INFINITY); + }); + + assert.strictEqual(is.positiveNumber(0), false); + assert.strictEqual(is.positiveNumber(-0), false); + assert.strictEqual(is.positiveNumber(-6), false); + assert.strictEqual(is.positiveNumber(-1.4), false); + assert.strictEqual(is.positiveNumber(Number.NEGATIVE_INFINITY), false); + assert.strictEqual(is.positiveNumber(Number.NaN), false); + + assert.throws(() => { + isAssert.positiveNumber(0); + }); + assert.throws(() => { + isAssert.positiveNumber(-0); + }); + assert.throws(() => { + isAssert.positiveNumber(-6); + }); + assert.throws(() => { + isAssert.positiveNumber(-1.4); + }); + assert.throws(() => { + isAssert.positiveNumber(Number.NEGATIVE_INFINITY); + }); +}); + +test('is.nan', () => { + assert.ok(is.nan(Number.NaN)); + assert.ok(is.nan(NaN)); // eslint-disable-line unicorn/prefer-number-properties + + assert.doesNotThrow(() => { + isAssert.nan(Number.NaN); + }); + + assert.strictEqual(is.nan(0), false); + assert.strictEqual(is.nan(-0), false); + assert.strictEqual(is.nan(1), false); + assert.strictEqual(is.nan(Number.POSITIVE_INFINITY), false); + assert.strictEqual(is.nan(Number.NEGATIVE_INFINITY), false); + assert.strictEqual(is.nan('NaN'), false); + assert.strictEqual(is.nan(undefined), false); + + assert.throws(() => { + isAssert.nan(0); + }); + assert.throws(() => { + isAssert.nan(1); + }); + assert.throws(() => { + isAssert.nan('NaN'); + }); +}); + +test('is.finiteNumber', () => { + assert.ok(is.finiteNumber(6)); + assert.ok(is.finiteNumber(-6)); + assert.ok(is.finiteNumber(0)); + assert.ok(is.finiteNumber(1.4)); + + assert.doesNotThrow(() => { + isAssert.finiteNumber(6); + }); + assert.doesNotThrow(() => { + isAssert.finiteNumber(0); + }); + + assert.strictEqual(is.finiteNumber(Number.POSITIVE_INFINITY), false); + assert.strictEqual(is.finiteNumber(Number.NEGATIVE_INFINITY), false); + assert.strictEqual(is.finiteNumber(Number.NaN), false); + + assert.throws(() => { + isAssert.finiteNumber(Number.POSITIVE_INFINITY); + }); + assert.throws(() => { + isAssert.finiteNumber(Number.NEGATIVE_INFINITY); + }); + assert.throws(() => { + isAssert.finiteNumber(Number.NaN); + }); +}); + +test('is.negativeNumber', () => { + assert.ok(is.negativeNumber(-6)); + assert.ok(is.negativeNumber(-1.4)); + assert.ok(is.negativeNumber(Number.NEGATIVE_INFINITY)); + + assert.doesNotThrow(() => { + isAssert.negativeNumber(-6); + }); + assert.doesNotThrow(() => { + isAssert.negativeNumber(-1.4); + }); + assert.doesNotThrow(() => { + isAssert.negativeNumber(Number.NEGATIVE_INFINITY); + }); + + assert.strictEqual(is.negativeNumber(0), false); + assert.strictEqual(is.negativeNumber(-0), false); + assert.strictEqual(is.negativeNumber(6), false); + assert.strictEqual(is.negativeNumber(1.4), false); + assert.strictEqual(is.negativeNumber(Number.POSITIVE_INFINITY), false); + assert.strictEqual(is.negativeNumber(Number.NaN), false); + + assert.throws(() => { + isAssert.negativeNumber(0); + }); + assert.throws(() => { + isAssert.negativeNumber(-0); + }); + assert.throws(() => { + isAssert.negativeNumber(6); + }); + assert.throws(() => { + isAssert.negativeNumber(1.4); + }); + assert.throws(() => { + isAssert.negativeNumber(Number.POSITIVE_INFINITY); + }); +}); + +test('is.nonNegativeNumber', () => { + assert.ok(is.nonNegativeNumber(0)); + assert.ok(is.nonNegativeNumber(6)); + assert.ok(is.nonNegativeNumber(1.4)); + assert.ok(is.nonNegativeNumber(Number.POSITIVE_INFINITY)); + + assert.doesNotThrow(() => { + isAssert.nonNegativeNumber(0); + }); + assert.doesNotThrow(() => { + isAssert.nonNegativeNumber(6); + }); + + assert.ok(is.nonNegativeNumber(-0)); // -0 >= 0 is true in JavaScript + assert.strictEqual(is.nonNegativeNumber(-6), false); + assert.strictEqual(is.nonNegativeNumber(-1.4), false); + assert.strictEqual(is.nonNegativeNumber(Number.NEGATIVE_INFINITY), false); + assert.strictEqual(is.nonNegativeNumber(Number.NaN), false); + + assert.throws(() => { + isAssert.nonNegativeNumber(-6); + }); + assert.throws(() => { + isAssert.nonNegativeNumber(Number.NEGATIVE_INFINITY); + }); +}); + +test('is.positiveInteger', () => { + assert.ok(is.positiveInteger(1)); + assert.ok(is.positiveInteger(6)); + assert.ok(is.positiveInteger(100)); + + assert.doesNotThrow(() => { + isAssert.positiveInteger(1); + }); + assert.doesNotThrow(() => { + isAssert.positiveInteger(6); + }); + + assert.strictEqual(is.positiveInteger(0), false); + assert.strictEqual(is.positiveInteger(-1), false); + assert.strictEqual(is.positiveInteger(1.5), false); + assert.strictEqual(is.positiveInteger(Number.POSITIVE_INFINITY), false); + assert.strictEqual(is.positiveInteger(Number.NaN), false); + + assert.throws(() => { + isAssert.positiveInteger(0); + }); + assert.throws(() => { + isAssert.positiveInteger(-1); + }); + assert.throws(() => { + isAssert.positiveInteger(1.5); + }); +}); + +test('is.negativeInteger', () => { + assert.ok(is.negativeInteger(-1)); + assert.ok(is.negativeInteger(-6)); + assert.ok(is.negativeInteger(-100)); + + assert.doesNotThrow(() => { + isAssert.negativeInteger(-1); + }); + assert.doesNotThrow(() => { + isAssert.negativeInteger(-6); + }); + + assert.strictEqual(is.negativeInteger(0), false); + assert.strictEqual(is.negativeInteger(-0), false); // -0 < 0 is false in JavaScript + assert.strictEqual(is.negativeInteger(1), false); + assert.strictEqual(is.negativeInteger(-1.5), false); + assert.strictEqual(is.negativeInteger(Number.NEGATIVE_INFINITY), false); + assert.strictEqual(is.negativeInteger(Number.NaN), false); + + assert.throws(() => { + isAssert.negativeInteger(0); + }); + assert.throws(() => { + isAssert.negativeInteger(1); + }); + assert.throws(() => { + isAssert.negativeInteger(-1.5); + }); + assert.throws(() => { + isAssert.negativeInteger(Number.NEGATIVE_INFINITY); + }); +}); + +test('is.nonNegativeInteger', () => { + assert.ok(is.nonNegativeInteger(0)); + assert.ok(is.nonNegativeInteger(1)); + assert.ok(is.nonNegativeInteger(100)); + + assert.doesNotThrow(() => { + isAssert.nonNegativeInteger(0); + }); + assert.doesNotThrow(() => { + isAssert.nonNegativeInteger(1); + }); + + assert.ok(is.nonNegativeInteger(-0)); // -0 >= 0 is true in JavaScript + + assert.strictEqual(is.nonNegativeInteger(-1), false); + assert.strictEqual(is.nonNegativeInteger(1.5), false); + assert.strictEqual(is.nonNegativeInteger(Number.POSITIVE_INFINITY), false); + assert.strictEqual(is.nonNegativeInteger(Number.NaN), false); + + assert.throws(() => { + isAssert.nonNegativeInteger(-1); + }); + assert.throws(() => { + isAssert.nonNegativeInteger(1.5); + }); + assert.throws(() => { + isAssert.nonNegativeInteger(Number.POSITIVE_INFINITY); + }); +}); + +test('is.infinite', () => { + assert.ok(is.infinite(Number.POSITIVE_INFINITY)); + assert.ok(is.infinite(Number.NEGATIVE_INFINITY)); + + assert.doesNotThrow(() => { + isAssert.infinite(Number.POSITIVE_INFINITY); + }); + assert.doesNotThrow(() => { + isAssert.infinite(Number.NEGATIVE_INFINITY); + }); + + assert.strictEqual(is.infinite(0), false); + assert.strictEqual(is.infinite(1), false); + assert.strictEqual(is.infinite(-1), false); + assert.strictEqual(is.infinite(Number.NaN), false); + assert.strictEqual(is.infinite(Number.MAX_VALUE), false); + assert.strictEqual(is.infinite('Infinity'), false); + + assert.throws(() => { + isAssert.infinite(0); + }); + assert.throws(() => { + isAssert.infinite(Number.NaN); + }); +}); + +test('is.numericString supplemental', () => { + assert.strictEqual(is.numericString(''), false); + assert.strictEqual(is.numericString(' '), false); + assert.strictEqual(is.numericString(' \t\t\n'), false); + assert.strictEqual(is.numericString(1), false); + assert.strictEqual(is.numericString(' 5'), false); + assert.strictEqual(is.numericString('5 '), false); + assert.strictEqual(is.numericString(' 5 '), false); + assert.strictEqual(is.numericString('\t3'), false); + assert.throws(() => { + isAssert.numericString(''); + }); + assert.throws(() => { + isAssert.numericString(1); + }); +}); + +test('is.array supplemental', () => { + assert.ok(is.array([1, 2, 3], is.number)); + assert.strictEqual(is.array([1, '2', 3], is.number), false); + + assert.doesNotThrow(() => { + isAssert.array([1, 2], isAssert.number); + }); + + assert.throws(() => { + isAssert.array([1, '2'], isAssert.number); + }); + + assert.doesNotThrow(() => { + const x: unknown[] = [1, 2, 3]; + isAssert.array(x, isAssert.number); + x[0]?.toFixed(0); + }); + + assert.doesNotThrow(() => { + const x: unknown[] = [1, 2, 3]; + if (is.array(x, is.number)) { + x[0]?.toFixed(0); + } + }); + + assert.throws(() => { + isAssert.array([1, '2'], isAssert.number, 'Expected numbers'); + }, /Expected numbers/v); +}); + +test('is.arrayOf', () => { + const isStringArray = is.arrayOf(is.string); + assert.ok(isStringArray(['a', 'b', 'c'])); + assert.ok(isStringArray([])); + assert.strictEqual(isStringArray([1, 2, 3]), false); + assert.strictEqual(isStringArray(['a', 1]), false); + assert.strictEqual(isStringArray('not an array'), false); + assert.strictEqual(isStringArray(undefined), false); + + const isNumberArray = is.arrayOf(is.number); + assert.ok(isNumberArray([1, 2, 3])); + assert.strictEqual(isNumberArray([1, '2']), false); +}); + +test('is.oneOf', () => { + const isDirection = is.oneOf(['north', 'south', 'east', 'west'] as const); + assert.ok(isDirection('north')); + assert.ok(isDirection('west')); + assert.strictEqual(isDirection('up'), false); + assert.strictEqual(isDirection(1), false); + assert.strictEqual(isDirection(undefined), false); + + const isSmallNumber = is.oneOf([1, 2, 3] as const); + assert.ok(isSmallNumber(1)); + assert.strictEqual(isSmallNumber(4), false); + + // Empty values array always returns false + const isNever = is.oneOf([] as const); + assert.strictEqual(isNever('anything'), false); + + // Array.includes uses SameValueZero, so NaN matches NaN (unlike ===) + const isNanValue = is.oneOf([Number.NaN] as const); + assert.ok(isNanValue(Number.NaN)); +}); + +test('is.boundFunction supplemental', () => { + assert.strictEqual(is.boundFunction(function () {}), false); // eslint-disable-line prefer-arrow-callback + + assert.throws(() => { + isAssert.boundFunction(function () {}); // eslint-disable-line prefer-arrow-callback + }); +}); + +test('is.asyncFunction supplemental', () => { + const fixture = async () => {}; + if (is.asyncFunction(fixture)) { + assert.ok(is.function(fixture().then)); + + assert.doesNotThrow(() => { + isAssert.function(fixture().then); + }); + } +}); + +test('is.asyncGenerator supplemental', () => { + const fixture = (async function * () { + yield 4; + })(); + if (is.asyncGenerator(fixture)) { + assert.ok(is.function(fixture.next)); + } +}); + +test('is.asyncGeneratorFunction supplemental', () => { + const fixture = async function * () { + yield 4; + }; + + if (is.asyncGeneratorFunction(fixture)) { + assert.ok(is.function(fixture().next)); + } +}); + +test('is.enumCase', () => { + enum NonNumericalEnum { + Key1 = 'key1', + Key2 = 'key2', + } + + enum NumericKeyStringEnum { + // eslint-disable-next-line @stylistic/quote-props + '0' = 'zero', + '01' = 'padded', + } + + assert.ok(is.enumCase('key1', NonNumericalEnum)); + assert.doesNotThrow(() => { + isAssert.enumCase('key1', NonNumericalEnum); + }); + + assert.strictEqual(is.enumCase('invalid', NonNumericalEnum), false); + assert.throws(() => { + isAssert.enumCase('invalid', NonNumericalEnum); + }); + + assert.ok(is.enumCase('zero', NumericKeyStringEnum)); + assert.ok(is.enumCase('padded', NumericKeyStringEnum)); + assert.doesNotThrow(() => { + isAssert.enumCase('zero', NumericKeyStringEnum); + }); + assert.doesNotThrow(() => { + isAssert.enumCase('padded', NumericKeyStringEnum); + }); + + enum NumericalEnum { + Key1 = 0, + Key2 = 1, + } + + assert.ok(is.enumCase(0, NumericalEnum)); + assert.ok(is.enumCase(1, NumericalEnum)); + assert.strictEqual(is.enumCase('Key1', NumericalEnum), false); + assert.strictEqual(is.enumCase('Key2', NumericalEnum), false); + assert.doesNotThrow(() => { + isAssert.enumCase(0, NumericalEnum); + }); + assert.throws(() => { + isAssert.enumCase('Key1', NumericalEnum); + }); + + enum HeterogeneousEnum { + A = 1, + B = 'hello', + } + + assert.ok(is.enumCase(1, HeterogeneousEnum)); + assert.ok(is.enumCase('hello', HeterogeneousEnum)); + assert.strictEqual(is.enumCase('A', HeterogeneousEnum), false); +}); + +test('is.directInstanceOf', () => { + const error = new Error('fixture'); + const errorSubclass = new ErrorSubclassFixture(); + + assert.ok(is.directInstanceOf(error, Error)); + assert.ok(is.directInstanceOf(errorSubclass, ErrorSubclassFixture)); + assert.doesNotThrow(() => { + isAssert.directInstanceOf(error, Error); + }); + assert.doesNotThrow(() => { + isAssert.directInstanceOf(errorSubclass, ErrorSubclassFixture); + }); + + assert.strictEqual(is.directInstanceOf(error, ErrorSubclassFixture), false); + assert.strictEqual(is.directInstanceOf(errorSubclass, Error), false); + assert.throws(() => { + isAssert.directInstanceOf(error, ErrorSubclassFixture); + }); + assert.throws(() => { + isAssert.directInstanceOf(errorSubclass, Error); + }); + + assert.strictEqual(is.directInstanceOf(undefined, Error), false); + assert.strictEqual(is.directInstanceOf(null, Error), false); +}); + +test('is.urlInstance', () => { + const url = new URL('https://example.com'); + assert.ok(is.urlInstance(url)); + assert.strictEqual(is.urlInstance({}), false); + assert.strictEqual(is.urlInstance(undefined), false); + assert.strictEqual(is.urlInstance(null), false); + + assert.doesNotThrow(() => { + isAssert.urlInstance(url); + }); + assert.throws(() => { + isAssert.urlInstance({}); + }); + assert.throws(() => { + isAssert.urlInstance(undefined); + }); + assert.throws(() => { + isAssert.urlInstance(null); + }); +}); + +test('is.urlString', () => { + const url = 'https://example.com'; + assert.ok(is.urlString(url)); + assert.strictEqual(is.urlString(new URL(url)), false); + assert.strictEqual(is.urlString({}), false); + assert.strictEqual(is.urlString(undefined), false); + assert.strictEqual(is.urlString(null), false); + + assert.doesNotThrow(() => { + isAssert.urlString(url); + }); + assert.throws(() => { + isAssert.urlString(new URL(url)); + }); + assert.throws(() => { + isAssert.urlString({}); + }); + assert.throws(() => { + isAssert.urlString(undefined); + }); + assert.throws(() => { + isAssert.urlString(null); + }); +}); + +// Type test for urlString narrowing fix (issue #212) +// This test demonstrates that the fix allows proper type narrowing in both branches +(() => { + const value: unknown = 'test'; + + if (is.urlString(value)) { + // ✅ In true branch: value is narrowed to UrlString + expectTypeOf(value).toEqualTypeOf(); + expectTypeOf(value).toMatchTypeOf(); + } else { + // ✅ In false branch: value remains unknown (not incorrectly narrowed) + expectTypeOf(value).toEqualTypeOf(); + + // ✅ Manual narrowing to string still works + if (typeof value === 'string') { + expectTypeOf(value).toEqualTypeOf(); + } + } +})(); + +// Type test for is.nan branded-type narrowing +(() => { + const value: unknown = Number.NaN; + + if (is.nan(value)) { + // ✅ In true branch: value is narrowed to the branded NaN type + expectTypeOf(value).toEqualTypeOf(); + expectTypeOf(value).toMatchTypeOf(); + } else { + // ✅ In false branch: value remains unknown (not incorrectly narrowed) + expectTypeOf(value).toEqualTypeOf(); + } +})(); + +test('is.truthy', () => { + assert.ok(is.truthy('unicorn')); + assert.ok(is.truthy('🦄')); + assert.ok(is.truthy(new Set())); + assert.ok(is.truthy(Symbol('🦄'))); + assert.ok(is.truthy(true)); + assert.ok(is.truthy(1)); + assert.ok(is.truthy(1n)); + + assert.doesNotThrow(() => { + isAssert.truthy('unicorn'); + }); + + assert.doesNotThrow(() => { + isAssert.truthy('🦄'); + }); + + assert.doesNotThrow(() => { + isAssert.truthy(new Set()); + }); + + assert.doesNotThrow(() => { + isAssert.truthy(Symbol('🦄')); + }); + + assert.doesNotThrow(() => { + isAssert.truthy(true); + }); + + assert.doesNotThrow(() => { + isAssert.truthy(1); + }); + + assert.doesNotThrow(() => { + isAssert.truthy(1n); + }); + + // Checks that `isAssert.truthy` narrow downs boolean type to `true`. + { + const booleans = [true, false]; + const function_ = (value: true) => value; + isAssert.truthy(booleans[0]); + function_(booleans[0]); + } + + // Checks that `isAssert.truthy` excludes zero value from number type. + { + const bits: Array<0 | 1> = [1, 0, -0]; + const function_ = (value: 1) => value; + isAssert.truthy(bits[0]); + function_(bits[0]); + } + + // Checks that `isAssert.truthy` excludes zero value from bigint type. + { + const bits: Array<0n | 1n> = [1n, 0n, -0n]; + const function_ = (value: 1n) => value; + isAssert.truthy(bits[0]); + function_(bits[0]); + } + + // Checks that `isAssert.truthy` excludes empty string from string type. + { + const strings: Array<'nonEmpty' | ''> = ['nonEmpty', '']; + const function_ = (value: 'nonEmpty') => value; + isAssert.truthy(strings[0]); + function_(strings[0]); + } + + // Checks that `isAssert.truthy` excludes undefined from mixed type. + { + const maybeUndefineds = ['🦄', undefined]; + const function_ = (value: string) => value; + isAssert.truthy(maybeUndefineds[0]); + function_(maybeUndefineds[0]); + } + + // Checks that `isAssert.truthy` excludes null from mixed type. + { + const maybeNulls = ['🦄', null]; + const function_ = (value: string) => value; + isAssert.truthy(maybeNulls[0]); + function_(maybeNulls[0]); + } +}); + +test('is.falsy', () => { + assert.ok(is.falsy(false)); + assert.ok(is.falsy(0)); + assert.ok(is.falsy('')); + assert.ok(is.falsy(null)); + assert.ok(is.falsy(undefined)); + assert.ok(is.falsy(Number.NaN)); + assert.ok(is.falsy(0n)); + + assert.doesNotThrow(() => { + isAssert.falsy(false); + }); + + assert.doesNotThrow(() => { + isAssert.falsy(0); + }); + + assert.doesNotThrow(() => { + isAssert.falsy(''); + }); + + assert.doesNotThrow(() => { + isAssert.falsy(null); + }); + + assert.doesNotThrow(() => { + isAssert.falsy(undefined); + }); + + assert.doesNotThrow(() => { + isAssert.falsy(Number.NaN); + }); + + assert.doesNotThrow(() => { + isAssert.falsy(0n); + }); + + // Checks that `isAssert.falsy` narrow downs boolean type to `false`. + { + const booleans = [false, true]; + const function_ = (value?: false) => value; + isAssert.falsy(booleans[0]); + function_(booleans[0]); + } + + // Checks that `isAssert.falsy` narrow downs number type to `0`. + { + const bits = [0, -0, 1]; + const function_ = (value?: 0) => value; + isAssert.falsy(bits[0]); + function_(bits[0]); + isAssert.falsy(bits[1]); + function_(bits[1]); + } + + // Checks that `isAssert.falsy` narrow downs bigint type to `0n`. + { + const bits = [0n, -0n, 1n]; + const function_ = (value?: 0n) => value; + isAssert.falsy(bits[0]); + function_(bits[0]); + isAssert.falsy(bits[1]); + function_(bits[1]); + } + + // Checks that `isAssert.falsy` narrow downs string type to empty string. + { + const strings = ['', 'nonEmpty']; + const function_ = (value?: '') => value; + isAssert.falsy(strings[0]); + function_(strings[0]); + } + + // Checks that `isAssert.falsy` can narrow down mixed type to undefined. + { + const maybeUndefineds = [undefined, Symbol('🦄')]; + const function_ = (value: undefined) => value; + isAssert.falsy(maybeUndefineds[0]); + function_(maybeUndefineds[0]); + } + + // Checks that `isAssert.falsy` can narrow down mixed type to null. + { + const maybeNulls = [null, Symbol('🦄')]; + // eslint-disable-next-line @typescript-eslint/no-restricted-types + const function_ = (value?: null) => value; + isAssert.falsy(maybeNulls[0]); + function_(maybeNulls[0]); + } +}); + +test('is.primitive', () => { + const primitives: Primitive[] = [ + undefined, + null, + '🦄', + 6, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + true, + false, + Symbol('🦄'), + 6n, + ]; + + for (const element of primitives) { + assert.ok(is.primitive(element)); + assert.doesNotThrow(() => { + isAssert.primitive(element); + }); + } +}); + +test('is.integer supplemental', () => { + assert.strictEqual(is.integer(1.4), false); + assert.throws(() => { + isAssert.integer(1.4); + }); +}); + +test('is.safeInteger supplemental', () => { + assert.strictEqual(is.safeInteger(2 ** 53), false); + assert.strictEqual(is.safeInteger(-(2 ** 53)), false); + assert.throws(() => { + isAssert.safeInteger(2 ** 53); + }); + assert.throws(() => { + isAssert.safeInteger(-(2 ** 53)); + }); +}); + +test('is.iterable', () => { + assert.ok(is.iterable('')); + assert.ok(is.iterable([])); + assert.ok(is.iterable(new Map())); + assert.strictEqual(is.iterable(null), false); + assert.strictEqual(is.iterable(undefined), false); + assert.strictEqual(is.iterable(0), false); + assert.strictEqual(is.iterable(Number.NaN), false); + assert.strictEqual(is.iterable(Number.POSITIVE_INFINITY), false); + assert.strictEqual(is.iterable({}), false); + + assert.doesNotThrow(() => { + isAssert.iterable(''); + }); + assert.doesNotThrow(() => { + isAssert.iterable([]); + }); + assert.doesNotThrow(() => { + isAssert.iterable(new Map()); + }); + assert.throws(() => { + isAssert.iterable(null); + }); + assert.throws(() => { + isAssert.iterable(undefined); + }); + assert.throws(() => { + isAssert.iterable(0); + }); + assert.throws(() => { + isAssert.iterable(Number.NaN); + }); + assert.throws(() => { + isAssert.iterable(Number.POSITIVE_INFINITY); + }); + assert.throws(() => { + isAssert.iterable({}); + }); +}); + +test('is.asyncIterable', () => { + assert.ok(is.asyncIterable({ + [Symbol.asyncIterator]() {}, + })); + + assert.strictEqual(is.asyncIterable(null), false); + assert.strictEqual(is.asyncIterable(undefined), false); + assert.strictEqual(is.asyncIterable(0), false); + assert.strictEqual(is.asyncIterable(Number.NaN), false); + assert.strictEqual(is.asyncIterable(Number.POSITIVE_INFINITY), false); + assert.strictEqual(is.asyncIterable({}), false); + + assert.doesNotThrow(() => { + isAssert.asyncIterable({ + [Symbol.asyncIterator]() {}, + }); + }); + + assert.throws(() => { + isAssert.asyncIterable(null); + }); + assert.throws(() => { + isAssert.asyncIterable(undefined); + }); + assert.throws(() => { + isAssert.asyncIterable(0); + }); + assert.throws(() => { + isAssert.asyncIterable(Number.NaN); + }); + assert.throws(() => { + isAssert.asyncIterable(Number.POSITIVE_INFINITY); + }); + assert.throws(() => { + isAssert.asyncIterable({}); + }); +}); + +test('is.class', () => { + class Foo {} // eslint-disable-line @typescript-eslint/no-extraneous-class + + // Note: Using new Function to test a minified class (no whitespace in source) + const minifiedClass = new Function('return class{};'); // eslint-disable-line no-new-func + + const classDeclarations = [ + Foo, + class Bar extends Foo {}, + minifiedClass(), + ]; + + for (const classDeclaration of classDeclarations) { + assert.ok(is.class(classDeclaration)); + + assert.doesNotThrow(() => { + isAssert.class(classDeclaration); + }); + } +}); + +test('is.typedArray', () => { + const typedArrays: TypedArray[] = [ + new Int8Array(), + new Uint8Array(), + new Uint8ClampedArray(), + new Int16Array(), + new Uint16Array(), + new Int32Array(), + new Uint32Array(), + new Float32Array(), + new Float64Array(), + new BigInt64Array(), + new BigUint64Array(), + ]; + + for (const item of typedArrays) { + assert.ok(is.typedArray(item)); + + assert.doesNotThrow(() => { + isAssert.typedArray(item); + }); + } + + assert.strictEqual(is.typedArray(new ArrayBuffer(1)), false); + assert.strictEqual(is.typedArray([]), false); + assert.strictEqual(is.typedArray({}), false); + + assert.throws(() => { + isAssert.typedArray(new ArrayBuffer(1)); + }); + assert.throws(() => { + isAssert.typedArray([]); + }); + assert.throws(() => { + isAssert.typedArray({}); + }); +}); + +test('is.arrayLike', () => { + (function () { + assert.ok(is.arrayLike(arguments)); // eslint-disable-line prefer-rest-params + })(); + + assert.ok(is.arrayLike([])); + assert.ok(is.arrayLike('unicorn')); + + assert.strictEqual(is.arrayLike({}), false); + assert.strictEqual(is.arrayLike(() => {}), false); + assert.strictEqual(is.arrayLike(new Map()), false); + + (function () { + assert.doesNotThrow(function () { + isAssert.arrayLike(arguments); // eslint-disable-line prefer-rest-params + }); + })(); + + assert.doesNotThrow(() => { + isAssert.arrayLike([]); + }); + assert.doesNotThrow(() => { + isAssert.arrayLike('unicorn'); + }); + + assert.throws(() => { + isAssert.arrayLike({}); + }); + assert.throws(() => { + isAssert.arrayLike(() => {}); + }); + assert.throws(() => { + isAssert.arrayLike(new Map()); + }); +}); + +test('is.tupleLike', () => { + (function () { + assert.strictEqual(is.tupleLike(arguments, []), false); // eslint-disable-line prefer-rest-params + })(); + + assert.ok(is.tupleLike([], [])); + assert.ok(is.tupleLike([1, '2', true, {}, [], undefined, null], [is.number, is.string, is.boolean, is.object, is.array, is.undefined, is.nullOrUndefined])); + assert.strictEqual(is.tupleLike('unicorn', [is.string]), false); + + assert.strictEqual(is.tupleLike({}, []), false); + assert.strictEqual(is.tupleLike(() => {}, [is.function]), false); + assert.strictEqual(is.tupleLike(new Map(), [is.map]), false); + + (function () { + assert.throws(function () { + isAssert.tupleLike(arguments, []); // eslint-disable-line prefer-rest-params + }); + })(); + + assert.doesNotThrow(() => { + isAssert.tupleLike([], []); + }); + assert.throws(() => { + isAssert.tupleLike('unicorn', [is.string]); + }); + + assert.throws(() => { + isAssert.tupleLike({}, [is.object]); + }); + assert.throws(() => { + isAssert.tupleLike(() => {}, [is.function]); + }); + assert.throws(() => { + isAssert.tupleLike(new Map(), [is.map]); + }); + + { + const tuple = [[false, 'unicorn'], 'string', true]; + + if (is.tupleLike(tuple, [is.array, is.string, is.boolean])) { + if (is.tupleLike(tuple[0], [is.boolean, is.string])) { // eslint-disable-line unicorn/no-lonely-if + const value = tuple[0][1]; + expectTypeOf(value).toEqualTypeOf(); + } + } + } + + { + const tuple = [{isTest: true}, '1', true, null]; + + if (is.tupleLike(tuple, [is.nonEmptyObject, is.string, is.boolean, is.null])) { + const value = tuple[0]; + expectTypeOf(value).toEqualTypeOf>(); + } + } + + { + const tuple = [1, '1', true, null, undefined]; + + if (is.tupleLike(tuple, [is.number, is.string, is.boolean, is.null, is.undefined])) { + const numericValue = tuple[0]; + const stringValue = tuple[1]; + const booleanValue = tuple[2]; + const nullValue = tuple[3]; + const undefinedValue = tuple[4]; + expectTypeOf(numericValue).toEqualTypeOf(); + expectTypeOf(stringValue).toEqualTypeOf(); + expectTypeOf(booleanValue).toEqualTypeOf(); + // eslint-disable-next-line @typescript-eslint/no-restricted-types + expectTypeOf(nullValue).toEqualTypeOf(); + expectTypeOf(undefinedValue).toEqualTypeOf(); + } + } +}); + +test('is.inRange', () => { + const x = 3; + + assert.ok(is.inRange(x, [0, 5])); + assert.ok(is.inRange(x, [5, 0])); + assert.ok(is.inRange(x, [-5, 5])); + assert.ok(is.inRange(x, [5, -5])); + assert.strictEqual(is.inRange(x, [4, 8]), false); + assert.ok(is.inRange(-7, [-5, -10])); + assert.ok(is.inRange(-5, [-5, -10])); + assert.ok(is.inRange(-10, [-5, -10])); + + assert.ok(is.inRange(x, 10)); + assert.ok(is.inRange(0, 0)); + assert.ok(is.inRange(-2, -3)); + assert.strictEqual(is.inRange(x, 2), false); + assert.strictEqual(is.inRange(-3, -2), false); + + assert.throws(() => { + // @ts-expect-error invalid argument + is.inRange(0, []); + }); + + assert.throws(() => { + // @ts-expect-error invalid argument + is.inRange(0, [5]); + }); + + assert.throws(() => { + // @ts-expect-error invalid argument + is.inRange(0, [1, 2, 3]); + }); + + assert.throws(() => { + is.inRange(5, [Number.NaN, 10]); + }, TypeError); + + assert.throws(() => { + is.inRange(5, [0, Number.NaN]); + }, TypeError); + + assert.doesNotThrow(() => { + isAssert.inRange(x, [0, 5]); + }); + + assert.doesNotThrow(() => { + isAssert.inRange(x, [5, 0]); + }); + + assert.doesNotThrow(() => { + isAssert.inRange(x, [-5, 5]); + }); + + assert.doesNotThrow(() => { + isAssert.inRange(x, [5, -5]); + }); + + assert.throws(() => { + isAssert.inRange(x, [4, 8]); + }); + + assert.doesNotThrow(() => { + isAssert.inRange(-7, [-5, -10]); + }); + + assert.doesNotThrow(() => { + isAssert.inRange(-5, [-5, -10]); + }); + + assert.doesNotThrow(() => { + isAssert.inRange(-10, [-5, -10]); + }); + + assert.doesNotThrow(() => { + isAssert.inRange(x, 10); + }); + + assert.doesNotThrow(() => { + isAssert.inRange(0, 0); + }); + + assert.doesNotThrow(() => { + isAssert.inRange(-2, -3); + }); + + assert.throws(() => { + isAssert.inRange(x, 2); + }); + + assert.throws(() => { + isAssert.inRange(-3, -2); + }); + + assert.throws(() => { + // @ts-expect-error invalid argument + isAssert.inRange(0, []); + }); + + assert.throws(() => { + // @ts-expect-error invalid argument + isAssert.inRange(0, [5]); + }); + + assert.throws(() => { + // @ts-expect-error invalid argument + isAssert.inRange(0, [1, 2, 3]); + }); +}); + +test('is.htmlElement supplemental', () => { + assert.strictEqual(is.htmlElement({nodeType: 1, nodeName: 'div'}), false); + assert.throws(() => { + isAssert.htmlElement({nodeType: 1, nodeName: 'div'}); + }); + + const tagNames = [ + 'div', + 'input', + 'span', + 'img', + 'canvas', + 'script', + ] as const; + + for (const tagName of tagNames) { + const element = document.createElement(tagName); + assert.strictEqual(is(element), 'HTMLElement'); + } + + const nonHtmlElements = [ + document.createTextNode('data'), + document.createProcessingInstruction('xml-stylesheet', 'href="mycss.css" type="text/css"'), + document.createComment('This is a comment'), + document, + document.implementation.createDocumentType('svg:svg', '-//W3C//DTD SVG 1.1//EN', 'https://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'), + document.createDocumentFragment(), + ] as const; + + for (const element of nonHtmlElements) { + assert.throws(() => { + isAssert.htmlElement(element); + }); + } +}); + +test('is.evenInteger', () => { + for (const element of [-6, 2, 4]) { + assert.ok(is.evenInteger(element)); + assert.doesNotThrow(() => { + isAssert.evenInteger(element); + }); + } + + for (const element of [-3, 1, 5]) { + assert.strictEqual(is.evenInteger(element), false); + assert.throws(() => { + isAssert.evenInteger(element); + }); + } +}); + +test('is.oddInteger', () => { + for (const element of [-5, 7, 13]) { + assert.ok(is.oddInteger(element)); + assert.doesNotThrow(() => { + isAssert.oddInteger(element); + }); + } + + for (const element of [-8, 8, 10]) { + assert.strictEqual(is.oddInteger(element), false); + assert.throws(() => { + isAssert.oddInteger(element); + }); + } +}); + +test('is.nonEmptyArray', () => { + assert.ok(is.nonEmptyArray([1, 2, 3])); + assert.strictEqual(is.nonEmptyArray([]), false); + assert.strictEqual(is.nonEmptyArray(new Array()), false); // eslint-disable-line @typescript-eslint/no-array-constructor + + assert.doesNotThrow(() => { + isAssert.nonEmptyArray([1, 2, 3]); + }); + assert.throws(() => { + isAssert.nonEmptyArray([]); + }); + assert.throws(() => { + isAssert.nonEmptyArray(new Array()); // eslint-disable-line @typescript-eslint/no-array-constructor + }); + + { + const strings = ['🦄', 'unicorn'] as string[] | undefined; + const function_ = (value: string) => value; + + if (is.nonEmptyArray(strings)) { + const value = strings[0]; + function_(value); + } + } + + { + const mixed = ['🦄', 'unicorn', 1, 2]; + const function_ = (value: string | number) => value; + + if (is.nonEmptyArray(mixed)) { + const value = mixed[0]; + function_(value); + } + } + + { + const arrays = [['🦄'], ['unicorn']]; + const function_ = (value: string[]) => value; + + if (is.nonEmptyArray(arrays)) { + const value = arrays[0]; + function_(value); + } + } + + { + const strings = ['🦄', 'unicorn'] as string[] | undefined; + const function_ = (value: string) => value; + + isAssert.nonEmptyArray(strings); + + const value = strings[0]; + function_(value); + } + + { + const mixed = ['🦄', 'unicorn', 1, 2]; + const function_ = (value: string | number) => value; + + isAssert.nonEmptyArray(mixed); + + const value = mixed[0]; + function_(value); + } + + { + const arrays = [['🦄'], ['unicorn']]; + const function_ = (value: string[]) => value; + + isAssert.nonEmptyArray(arrays); + + const value = arrays[0]; + function_(value); + } +}); + +test('is.emptyString supplemental', () => { + assert.strictEqual(is.emptyString('🦄'), false); + assert.throws(() => { + isAssert.emptyString('🦄'); + }); +}); + +test('is.emptyStringOrWhitespace supplemental', () => { + assert.ok(is.emptyStringOrWhitespace(' ')); + assert.strictEqual(is.emptyStringOrWhitespace('🦄'), false); + assert.strictEqual(is.emptyStringOrWhitespace('unicorn'), false); + + assert.doesNotThrow(() => { + isAssert.emptyStringOrWhitespace(' '); + }); + assert.throws(() => { + isAssert.emptyStringOrWhitespace('🦄'); + }); + assert.throws(() => { + isAssert.emptyStringOrWhitespace('unicorn'); + }); + + let value = 'test'; // eslint-disable-line prefer-const -- can't use `const` here because then it will be inferred as `never` in the `if` block + if (is.emptyStringOrWhitespace(value)) { + value.charAt(0); // Should be inferred as `'' | Whitespace` and not `never` + } else { + value.charAt(0); // Should be inferred as `string` and not `never` + } +}); + +test('is.nonEmptyString', () => { + assert.strictEqual(is.nonEmptyString(''), false); + assert.strictEqual(is.nonEmptyString(String()), false); + assert.ok(is.nonEmptyString('🦄')); + + assert.throws(() => { + isAssert.nonEmptyString(''); + }); + assert.throws(() => { + isAssert.nonEmptyString(String()); + }); + assert.doesNotThrow(() => { + isAssert.nonEmptyString('🦄'); + }); +}); + +test('is.nonEmptyStringAndNotWhitespace', () => { + assert.strictEqual(is.nonEmptyStringAndNotWhitespace(' '), false); + assert.ok(is.nonEmptyStringAndNotWhitespace('🦄')); + + for (const value of [null, undefined, 5, Number.NaN, {}, []]) { + assert.strictEqual(is.nonEmptyStringAndNotWhitespace(value), false); + + assert.throws(() => { + isAssert.nonEmptyStringAndNotWhitespace(value); + }); + } + + assert.throws(() => { + isAssert.nonEmptyStringAndNotWhitespace(''); + }); + + assert.doesNotThrow(() => { + isAssert.nonEmptyStringAndNotWhitespace('🦄'); + }); +}); + +test('is.emptyObject', () => { + assert.ok(is.emptyObject({})); + assert.ok(is.emptyObject(new Object())); // eslint-disable-line no-object-constructor + assert.strictEqual(is.emptyObject({unicorn: '🦄'}), false); + assert.strictEqual(is.emptyObject(function () {}), false); // eslint-disable-line prefer-arrow-callback + assert.strictEqual(is.emptyObject(() => {}), false); + assert.strictEqual(is.emptyObject(class Foo {}), false); // eslint-disable-line @typescript-eslint/no-extraneous-class + assert.strictEqual(is.emptyObject([]), false); + assert.strictEqual(is.emptyObject(['unicorn']), false); + + assert.doesNotThrow(() => { + isAssert.emptyObject({}); + }); + assert.doesNotThrow(() => { + isAssert.emptyObject(new Object()); // eslint-disable-line no-object-constructor + }); + assert.throws(() => { + isAssert.emptyObject({unicorn: '🦄'}); + }); + assert.throws(() => { + isAssert.emptyObject(function () {}); // eslint-disable-line prefer-arrow-callback + }); +}); + +test('is.nonEmptyObject', () => { + const foo = {}; + is.nonEmptyObject(foo); + + assert.strictEqual(is.nonEmptyObject({}), false); + assert.strictEqual(is.nonEmptyObject(new Object()), false); // eslint-disable-line no-object-constructor + assert.ok(is.nonEmptyObject({unicorn: '🦄'})); + + assert.strictEqual(is.nonEmptyObject([]), false); + assert.strictEqual(is.nonEmptyObject(['unicorn']), false); + + const functionWithProperty = function () {}; + (functionWithProperty as any).custom = 'value'; + assert.strictEqual(is.nonEmptyObject(functionWithProperty), false); + + assert.throws(() => { + isAssert.nonEmptyObject({}); + }); + assert.throws(() => { + isAssert.nonEmptyObject(new Object()); // eslint-disable-line no-object-constructor + }); + assert.doesNotThrow(() => { + isAssert.nonEmptyObject({unicorn: '🦄'}); + }); +}); + +test('is.nonEmptySet', () => { + const temporarySet = new Set(); + assert.strictEqual(is.nonEmptySet(temporarySet), false); + assert.throws(() => { + isAssert.nonEmptySet(temporarySet); + }); + + temporarySet.add(1); + assert.ok(is.nonEmptySet(temporarySet)); + assert.doesNotThrow(() => { + isAssert.nonEmptySet(temporarySet); + }); +}); + +test('is.nonEmptyMap', () => { + const temporaryMap = new Map(); + assert.strictEqual(is.nonEmptyMap(temporaryMap), false); + assert.throws(() => { + isAssert.nonEmptyMap(temporaryMap); + }); + + temporaryMap.set('unicorn', '🦄'); + assert.ok(is.nonEmptyMap(temporaryMap)); + assert.doesNotThrow(() => { + isAssert.nonEmptyMap(temporaryMap); + }); +}); + +test('is.propertyKey', () => { + assert.ok(is.propertyKey('key')); + assert.ok(is.propertyKey(42)); + assert.ok(is.propertyKey(Symbol(''))); + + assert.strictEqual(is.propertyKey(null), false); + assert.strictEqual(is.propertyKey(undefined), false); + assert.strictEqual(is.propertyKey(true), false); + assert.strictEqual(is.propertyKey({}), false); + assert.strictEqual(is.propertyKey([]), false); + assert.strictEqual(is.propertyKey(new Map()), false); + assert.strictEqual(is.propertyKey(new Set()), false); + + // AssertPropertyKey should narrow to PropertyKey (string | number | symbol), not just number + const symbolValue: unknown = Symbol('test'); + assertPropertyKey(symbolValue); + expectTypeOf(symbolValue).toEqualTypeOf(); +}); + +test('is.any', () => { + assert.ok(is.any(is.string, {}, true, '🦄')); + assert.ok(is.any(is.object, false, {}, 'unicorns')); + assert.strictEqual(is.any(is.boolean, '🦄', [], 3), false); + assert.strictEqual(is.any(is.integer, true, 'lol', {}), false); + assert.ok(is.any([is.string, is.number], {}, true, '🦄')); + assert.strictEqual(is.any([is.boolean, is.number], 'unicorns', [], new Map()), false); + assert.strictEqual(typeof is.any([is.string, is.number]), 'function'); + + assert.throws(() => { + is.any(null as any, true); + }); + + assert.throws(() => { + is.any([], 'value'); + }); + + assert.throws(() => { + is.any(is.string); + }); + + assert.doesNotThrow(() => { + isAssert.any(is.string, {}, true, '🦄'); + }); + + assert.doesNotThrow(() => { + isAssert.any(is.object, false, {}, 'unicorns'); + }); + + assert.throws(() => { + isAssert.any([is.string, is.number]); + }); + + assert.throws(() => { + isAssert.any(is.boolean, '🦄', [], 3); + }); + + assert.throws(() => { + isAssert.any(is.integer, true, 'lol', {}); + }); + + assert.throws(() => { + isAssert.any(null as any, true); + }); + + assert.throws(() => { + isAssert.any([], 'value'); + }); + + assert.throws(() => { + isAssert.any(is.string); + }); + + assert.throws(() => { + isAssert.any(is.string, 1, 2, 3); + }, { + // Includes expected type and removes duplicates from received types: + // eslint-disable-next-line prefer-regex-literals + message: new RegExp('Expected values which are `string`. Received values of type `number`.', 'v'), + }); + + assert.throws(() => { + isAssert.any(is.string, 1, [4]); + }, { + // Includes expected type and lists all received types: + // eslint-disable-next-line prefer-regex-literals + message: new RegExp('Expected values which are `string`. Received values of types `number` and `Array`.', 'v'), + }); + + assert.throws(() => { + isAssert.any([is.string, is.nullOrUndefined], 1); + }, { + // Handles array as first argument: + // eslint-disable-next-line prefer-regex-literals + message: new RegExp('Expected values which are `string` or `null or undefined`. Received values of type `number`.', 'v'), + }); + + assert.throws(() => { + isAssert.any([is.string, is.number, is.boolean], null, undefined, Number.NaN); + }, { + // Handles more than 2 expected and received types: + // eslint-disable-next-line prefer-regex-literals + message: new RegExp('Expected values which are `string`, `number`, or `boolean`. Received values of types `null`, `undefined`, and `NaN`.', 'v'), + }); + + assert.throws(() => { + isAssert.any(() => false, 1); + }, { + // Default type assertion message + // eslint-disable-next-line prefer-regex-literals + message: new RegExp('Expected values which are `predicate returns truthy for any value`.', 'v'), + }); +}); + +test('is.all', () => { + assert.ok(is.all(is.object, {}, new Set(), new Map())); + assert.ok(is.all(is.boolean, true, false)); + assert.strictEqual(is.all(is.string, '🦄', []), false); + assert.strictEqual(is.all(is.set, new Map(), {}), false); + + assert.ok(is.all(is.array, ['1'], ['2'])); + assert.ok(is.all([is.string, is.nonEmptyString], '🦄', 'unicorns')); + assert.strictEqual(is.all([is.string, is.number], '🦄'), false); + + assert.throws(() => { + is.all(null as any, true); + }); + + assert.throws(() => { + is.all([], 'value'); + }); + + assert.throws(() => { + is.all(is.string); + }); + + assert.doesNotThrow(() => { + isAssert.all(is.object, {}, new Set(), new Map()); + }); + + assert.doesNotThrow(() => { + isAssert.all(is.boolean, true, false); + }); + + assert.throws(() => { + isAssert.all([is.string, is.number]); + }); + + assert.doesNotThrow(() => { + isAssert.all([is.string, is.nonEmptyString], '🦄', 'unicorns'); + }); + + assert.throws(() => { + isAssert.all(is.string, '🦄', []); + }); + + assert.throws(() => { + isAssert.all([is.string, is.number], '🦄'); + }); + + assert.throws(() => { + isAssert.all(is.set, new Map(), {}); + }); + + assert.throws(() => { + isAssert.all(null as any, true); + }); + + assert.throws(() => { + isAssert.all([], 'value'); + }); + + assert.throws(() => { + isAssert.all(is.string); + }); + + assert.throws(() => { + isAssert.all(is.string, 1, 2, 3); + }, { + // Includes expected type and removes duplicates from received types: + // eslint-disable-next-line prefer-regex-literals + message: new RegExp('Expected values which are `string`. Received values of type `number`.', 'v'), + }); + + assert.throws(() => { + isAssert.all(is.string, 1, [4]); + }, { + // Includes expected type and lists all received types: + // eslint-disable-next-line prefer-regex-literals + message: new RegExp('Expected values which are `string`. Received values of types `number` and `Array`.', 'v'), + }); + + assert.throws(() => { + isAssert.all(() => false, 1); + }, { + // Default type assertion message + // eslint-disable-next-line prefer-regex-literals + message: new RegExp('Expected values which are `predicate returns truthy for all values`.', 'v'), + }); +}); + +test('is.any as predicate factory', () => { + // Returns a type guard function when called with only predicates + const isStringOrNumber = is.any([is.string, is.number]); + assert.strictEqual(typeof isStringOrNumber, 'function'); + assert.ok(isStringOrNumber('hello')); + assert.ok(isStringOrNumber(123)); + assert.strictEqual(isStringOrNumber(true), false); + assert.strictEqual(isStringOrNumber({}), false); + + // Type narrowing works correctly (compile-time check) + const value: unknown = 'test'; + if (isStringOrNumber(value)) { + // TypeScript should narrow to string | number + const narrowed: string | number = value; + assert.ok(typeof narrowed === 'string' || typeof narrowed === 'number'); + } + + // Works with is.optional + assert.ok(is.optional(undefined, is.any([is.string, is.number]))); + assert.ok(is.optional('test', is.any([is.string, is.number]))); + assert.ok(is.optional(42, is.any([is.string, is.number]))); + assert.strictEqual(is.optional(true, is.any([is.string, is.number])), false); + + const predicateArray: Predicate[] = [is.string, is.number]; + const isStringOrNumberFromArray = is.any(predicateArray); + assert.strictEqual(typeof isStringOrNumberFromArray, 'function'); + assert.ok(isStringOrNumberFromArray('hello')); + assert.ok(isStringOrNumberFromArray(123)); + assert.strictEqual(isStringOrNumberFromArray(true), false); + + // Type narrowing with is.optional (compile-time check) + const optionalValue: unknown = undefined; + if (is.optional(optionalValue, is.any([is.string, is.number]))) { + // TypeScript should narrow to string | number | undefined + const narrowed: string | number | undefined = optionalValue; + assert.ok(narrowed === undefined || typeof narrowed === 'string' || typeof narrowed === 'number'); + } + + // Works with more predicates + const isStringOrNumberOrBoolean = is.any([is.string, is.number, is.boolean]); + assert.ok(isStringOrNumberOrBoolean('hello')); + assert.ok(isStringOrNumberOrBoolean(123)); + assert.ok(isStringOrNumberOrBoolean(true)); + assert.strictEqual(isStringOrNumberOrBoolean({}), false); + + assert.throws(() => { + is.any([is.string, 123 as any]); + }); +}); + +test('is.all as predicate factory', () => { + // Returns a type guard function when called with only predicates + const isArrayAndNonEmpty = is.all([is.array, is.nonEmptyArray]); + assert.strictEqual(typeof isArrayAndNonEmpty, 'function'); + assert.ok(isArrayAndNonEmpty(['hello'])); + assert.strictEqual(isArrayAndNonEmpty([]), false); + assert.strictEqual(isArrayAndNonEmpty('hello'), false); + + // Type narrowing works correctly + const value: unknown = ['test']; + if (isArrayAndNonEmpty(value)) { + // TypeScript should narrow to the intersection type + assert.ok(Array.isArray(value)); + assert.ok(value.length > 0); + } + + // Works with is.optional + assert.ok(is.optional(undefined, is.all([is.object, is.plainObject]))); + assert.ok(is.optional({foo: 'bar'}, is.all([is.object, is.plainObject]))); + assert.strictEqual(is.optional([], is.all([is.object, is.plainObject])), false); + + assert.throws(() => { + is.all([is.string, 123 as any]); + }); +}); + +test('is.formData supplemental', () => { + const data = new window.FormData(); + assert.ok(is.formData(data)); + assert.strictEqual(is.formData({}), false); + assert.strictEqual(is.formData(undefined), false); + assert.strictEqual(is.formData(null), false); + + assert.doesNotThrow(() => { + isAssert.formData(data); + }); + assert.throws(() => { + isAssert.formData({}); + }); + assert.throws(() => { + isAssert.formData(undefined); + }); + assert.throws(() => { + isAssert.formData(null); + }); +}); + +test('is.urlSearchParams', () => { + const searchParameters = new URLSearchParams(); + assert.ok(is.urlSearchParams(searchParameters)); + assert.strictEqual(is.urlSearchParams({}), false); + assert.strictEqual(is.urlSearchParams(undefined), false); + assert.strictEqual(is.urlSearchParams(null), false); + + assert.doesNotThrow(() => { + isAssert.urlSearchParams(searchParameters); + }); + assert.throws(() => { + isAssert.urlSearchParams({}); + }); + assert.throws(() => { + isAssert.urlSearchParams(undefined); + }); + assert.throws(() => { + isAssert.urlSearchParams(null); + }); +}); + +test('is.validDate', () => { + assert.ok(is.validDate(new Date())); + assert.strictEqual(is.validDate(new Date('x')), false); + assert.doesNotThrow(() => { + isAssert.validDate(new Date()); + }); + assert.throws(() => { + isAssert.validDate(new Date('x')); + }); +}); + +test('is.validLength', () => { + assert.ok(is.validLength(1)); + assert.ok(is.validLength(0)); + assert.strictEqual(is.validLength(-1), false); + assert.strictEqual(is.validLength(0.1), false); + assert.doesNotThrow(() => { + isAssert.validLength(1); + }); + assert.throws(() => { + isAssert.validLength(-1); + }); + assert.throws(() => { + isAssert.validLength(0.1); + }); +}); + +test('is.whitespaceString', () => { + assert.ok(is.whitespaceString(' ')); + assert.ok(is.whitespaceString(' ')); + assert.ok(is.whitespaceString('   ')); + assert.ok(is.whitespaceString('\u3000')); + assert.ok(is.whitespaceString(' ')); + assert.strictEqual(is.whitespaceString(''), false); + assert.strictEqual(is.whitespaceString('-'), false); + assert.strictEqual(is.whitespaceString(' hi '), false); + + assert.doesNotThrow(() => { + isAssert.whitespaceString(' '); + }); + assert.throws(() => { + isAssert.whitespaceString(''); + }); + assert.throws(() => { + isAssert.whitespaceString(' hi '); + }); +}); + +test('assert', () => { + // Contrived test showing that TypeScript acknowledges the type assertion in `isAssert.number()`. + // Real-world usage includes asserting user input, but here we use a random number/string generator. + + const getNumberOrStringRandomly = (): number | string => { + const random = Math.random(); + + if (random < 0.5) { + return 'sometimes this function returns text'; + } + + return random; + }; + + const canUseOnlyNumber = (badlyTypedArgument: any): number => { + // Narrow the type to number, or throw an error at runtime for non-numbers. + isAssert.number(badlyTypedArgument); + + // Both the type and runtime value is number. + return 1000 * badlyTypedArgument; + }; + + const badlyTypedVariable: any = getNumberOrStringRandomly(); + + assert.ok(is.number(badlyTypedVariable) || is.string(badlyTypedVariable)); + + // Using try/catch for test purposes only. + try { + const result = canUseOnlyNumber(badlyTypedVariable); + + // Got lucky, the input was a number yielding a good result. + assert.ok(is.number(result)); + } catch { + // Assertion was tripped. + assert.ok(is.string(badlyTypedVariable)); + } +}); + +test('custom assertion message', () => { + const message = 'Custom error message'; + + const assertThrowsTypeErrorWithMessage = (assertion: () => void) => { + // `node:assert` does not verify the error class when matching only on `{message}`. + assert.throws(assertion, error => { + assert.ok(error instanceof TypeError); + assert.strictEqual(error.message, message); + return true; + }); + }; + + assertThrowsTypeErrorWithMessage(() => { + isAssert.array(undefined, undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.arrayBuffer(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.arrayLike(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.asyncFunction(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.asyncGenerator(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.asyncGeneratorFunction(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.asyncIterable(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.bigInt64Array(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.bigUint64Array(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.bigint(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.blob(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.boolean(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.boundFunction(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.buffer(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.class(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.dataView(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.date(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.directInstanceOf(undefined, Error, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.emptyArray(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.emptyMap(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.emptyObject(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.emptySet(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.emptyString(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.emptyStringOrWhitespace(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + enum Enum {} + isAssert.enumCase('invalid', Enum, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.error(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.evenInteger(33, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.falsy(true, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.finiteNumber(Number.POSITIVE_INFINITY, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.float32Array(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.float64Array(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.formData(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.function(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.generator(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.generatorFunction(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.htmlElement(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.inRange(5, [1, 2], message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.infinite(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.int16Array(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.int32Array(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.int8Array(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.integer(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.iterable(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.map(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.nan(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.nativePromise(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.not.undefined(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.not.string('hello', message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.negativeNumber(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.nodeStream(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.nonEmptyArray(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.nonEmptyMap(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.nonEmptyObject(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.nonEmptySet(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.nonEmptyString(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.nonEmptyStringAndNotWhitespace(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.nonNegativeNumber(-1, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.null(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.nullOrUndefined(false, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.number(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.numericString(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.object(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.observable(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.oddInteger(42, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.plainObject(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.positiveInteger(0, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.positiveNumber(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.primitive([], message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.promise(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.propertyKey(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.regExp(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.safeInteger(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.set(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.sharedArrayBuffer(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.string(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.symbol(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.truthy(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.tupleLike(undefined, [], message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.typedArray(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.uint16Array(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.uint32Array(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.uint8Array(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.uint8ClampedArray(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.undefined(false, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.urlInstance(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.urlSearchParams(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.urlString(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.validDate(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.validLength(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.weakMap(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.weakRef(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.weakSet(undefined, message); + }); + + assertThrowsTypeErrorWithMessage(() => { + isAssert.whitespaceString(undefined, message); + }); +}); + +test('isAssert.not.undefined', () => { + assert.throws(() => { + isAssert.not.undefined(undefined); + }, { + message: 'Expected value which is not `undefined`, received value of type `undefined`.', + }); + + assert.doesNotThrow(() => { + isAssert.not.undefined(null); + }); + + assert.doesNotThrow(() => { + isAssert.not.undefined(false); + }); + + assert.doesNotThrow(() => { + isAssert.not.undefined(0); + }); + + assert.doesNotThrow(() => { + isAssert.not.undefined(''); + }); +}); + +test('isAssert.not', () => { + assert.deepStrictEqual(new Set(keysOf(isAssert.not)), new Set(keysOf(notAssertionFixtures))); + + for (const type of keysOf(notAssertionFixtures)) { + const {nonFixture, typeDescription} = notAssertionFixtures[type]; + const testAssert = isAssert.not[type]; + const fixtures = 'fixtures' in notAssertionFixtures[type] ? notAssertionFixtures[type].fixtures : [notAssertionFixtures[type].fixture]; + + for (const fixture of fixtures) { + assert.throws(() => { + testAssert(fixture); + }, { + message: `Expected value which is not \`${typeDescription}\`, received value of type \`${is(fixture)}\`.`, + }); + } + + assert.doesNotThrow(() => { + testAssert(nonFixture); + }); + } + + assert.strictEqual('number' in isAssert.not, false); + assert.strictEqual('integer' in isAssert.not, false); + assert.strictEqual('object' in isAssert.not, false); + assert.strictEqual('blob' in isAssert.not, false); + assert.strictEqual('array' in isAssert.not, false); + assert.strictEqual('date' in isAssert.not, false); + assert.strictEqual('function' in isAssert.not, false); + assert.strictEqual('map' in isAssert.not, false); + assert.strictEqual('set' in isAssert.not, false); +}); + +test('isAssert.not edge cases', () => { + assert.doesNotThrow(() => { + isAssert.not.null(undefined); + }); +}); + +test('is.optional', () => { + assert.ok(is.optional(undefined, is.string)); + assert.ok(is.optional('🦄', is.string)); + assert.strictEqual(is.optional(123, is.string), false); + assert.strictEqual(is.optional(null, is.string), false); +}); + +test('isAssert.optional', () => { + assert.doesNotThrow(() => { + isAssert.optional(undefined, isAssert.string); + }); + + assert.doesNotThrow(() => { + isAssert.optional('🦄', isAssert.string); + }); + + assert.throws(() => { + isAssert.optional(123, isAssert.string); + }); + + assert.throws(() => { + isAssert.optional(null, isAssert.string); + }); +}); diff --git a/test/tsconfig.json b/test/tsconfig.json new file mode 100644 index 0000000..1f492d3 --- /dev/null +++ b/test/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "rootDir": "..", + "noUnusedLocals": false, + "noUnusedParameters": false + }, + "include": [ + "../source", + "type-tests.ts" + ] +} diff --git a/test/type-tests.ts b/test/type-tests.ts new file mode 100644 index 0000000..f08fa25 --- /dev/null +++ b/test/type-tests.ts @@ -0,0 +1,405 @@ +import {expectTypeOf} from 'expect-type'; +import is, { + assert as isAssert, + assertNotNullOrUndefined, + assertNotPrimitive, + assertNotString, + assertNotUndefined, + type EvenInteger, + type FiniteNumber, + type Integer, + type NaN as NaNType, + type NegativeInfinity, + type NegativeInteger, + type NegativeNumber, + type NonNegativeInteger, + type NonNegativeNumber, + type OddInteger, + type PositiveInfinity, + type PositiveInteger, + type PositiveNumber, + type Primitive, + type SafeInteger, + type ValidLength, +} from '../source/index.ts'; + +// eslint-disable-next-line @typescript-eslint/no-restricted-types +type UnknownNotPrimitive = Exclude | object; + +// For each predicate, verify two things: +// 1. True branch narrows to the branded type. +// 2. False branch on a `number` input stays `number` (not `never`). +// Without the branded types, `Exclude` = `never` would break +// the common validation-guard pattern: if (!is.X(n)) throw; use(n). + +const nanCheck = (value: number) => { + if (is.nan(value)) { + const _: NaNType = value; + } else { + const _: number = value; + } +}; + +const finiteNumberCheck = (value: number) => { + if (is.finiteNumber(value)) { + const _: FiniteNumber = value; + } else { + const _: number = value; + } +}; + +const nonNegativeNumberCheck = (value: number) => { + if (is.nonNegativeNumber(value)) { + const _: NonNegativeNumber = value; + } else { + const _: number = value; + } +}; + +const positiveIntegerCheck = (value: number) => { + if (is.positiveInteger(value)) { + const _: PositiveInteger = value; + const __: Integer = value; + const ___: NonNegativeInteger = value; + } else { + const _: number = value; + } +}; + +const negativeIntegerCheck = (value: number) => { + if (is.negativeInteger(value)) { + const _: NegativeInteger = value; + const __: Integer = value; + } else { + const _: number = value; + } +}; + +const nonNegativeIntegerCheck = (value: number) => { + if (is.nonNegativeInteger(value)) { + const _: NonNegativeInteger = value; + const __: Integer = value; + } else { + const _: number = value; + } +}; + +const infiniteCheck = (value: number) => { + if (is.infinite(value)) { + const _: PositiveInfinity | NegativeInfinity = value; + const __: PositiveNumber | NegativeNumber = value; + } else { + const _: number = value; + } +}; + +const integerCheck = (value: number) => { + if (is.integer(value)) { + const _: Integer = value; + const __: FiniteNumber = value; + } else { + const _: number = value; + } +}; + +const safeIntegerCheck = (value: number) => { + if (is.safeInteger(value)) { + const _: SafeInteger = value; + const __: Integer = value; + } else { + const _: number = value; + } +}; + +const evenIntegerCheck = (value: number) => { + if (is.evenInteger(value)) { + const _: EvenInteger = value; + const __: Integer = value; + } else { + const _: number = value; + } +}; + +const oddIntegerCheck = (value: number) => { + if (is.oddInteger(value)) { + const _: OddInteger = value; + const __: Integer = value; + } else { + const _: number = value; + } +}; + +const positiveNumberCheck = (value: number) => { + if (is.positiveNumber(value)) { + const _: PositiveNumber = value; + const __: NonNegativeNumber = value; + } else { + const _: number = value; + } +}; + +const negativeNumberCheck = (value: number) => { + if (is.negativeNumber(value)) { + const _: NegativeNumber = value; + } else { + const _: number = value; + } +}; + +const validLengthCheck = (value: number) => { + if (is.validLength(value)) { + const _: ValidLength = value; + const __: SafeInteger = value; + const ___: NonNegativeInteger = value; + } else { + const _: number = value; + } +}; + +const integerUnknownCheck = (value: unknown) => { + if (is.integer(value)) { + const _: Integer = value; + const __: FiniteNumber = value; + } +}; + +const positiveIntegerUnknownCheck = (value: unknown) => { + if (is.positiveInteger(value)) { + const _: PositiveInteger = value; + const __: NonNegativeInteger = value; + } +}; + +const integerMixedUnionCheck = (value: string | number) => { + if (is.integer(value)) { + const _: number = value; + } else { + const _: string = value; + } +}; + +const positiveNumberMixedUnionCheck = (value: string | number) => { + if (is.positiveNumber(value)) { + const _: number = value; + } else { + const _: string = value; + } +}; + +const chainedNumericGuardCheck = (value: number) => { + if (is.positiveNumber(value) && is.integer(value)) { + const _: PositiveNumber = value; + const __: Integer = value; + const ___: FiniteNumber = value; + } +}; + +const distinctNumericBrandsStayDistinct = ( + positiveInteger: PositiveInteger, + negativeInteger: NegativeInteger, + validLength: ValidLength, +) => { + // @ts-expect-error -- Distinct numeric refinements must not collapse into each other. + const _: NegativeInteger = positiveInteger; + // @ts-expect-error -- ValidLength is non-negative and must not become a signed integer refinement. + const __: NegativeInteger = validLength; + + return negativeInteger; +}; + +const assertNotUndefinedCheck = (value: string | undefined) => { + isAssert.not.undefined(value); + expectTypeOf(value).toEqualTypeOf(); +}; + +const assertNotUndefinedUnknownCheck = (value: unknown) => { + isAssert.not.undefined(value); + expectTypeOf(value).toEqualTypeOf>(); +}; + +const assertNotUndefinedGenericCheck = (value: T) => { + isAssert.not.undefined(value); + const _: Exclude = value; +}; + +const nullValue = null; +type Null = typeof nullValue; + +const assertNotNullUnknownCheck = (value: unknown) => { + isAssert.not.null(value); + expectTypeOf(value).toEqualTypeOf>(); +}; + +const assertNotNullOrUndefinedCheck = (value: string | Null | undefined) => { + isAssert.not.nullOrUndefined(value); + expectTypeOf(value).toEqualTypeOf(); +}; + +const assertNotNullOrUndefinedUnknownCheck = (value: unknown) => { + isAssert.not.nullOrUndefined(value); + expectTypeOf(value).toEqualTypeOf>(); +}; + +const assertNotStringCheck = (value: string | number) => { + isAssert.not.string(value); + expectTypeOf(value).toEqualTypeOf(); +}; + +const assertNotStringUnknownCheck = (value: unknown) => { + isAssert.not.string(value); + expectTypeOf(value).toEqualTypeOf>(); +}; + +const assertNotStringGenericCheck = (value: T) => { + isAssert.not.string(value); + const _: Exclude = value; +}; + +const assertNotBooleanUnknownCheck = (value: unknown) => { + isAssert.not.boolean(value); + expectTypeOf(value).toEqualTypeOf>(); +}; + +const assertNotSymbolUnknownCheck = (value: unknown) => { + isAssert.not.symbol(value); + expectTypeOf(value).toEqualTypeOf>(); +}; + +const assertNotBigintUnknownCheck = (value: unknown) => { + isAssert.not.bigint(value); + expectTypeOf(value).toEqualTypeOf>(); +}; + +const assertNotPrimitiveUnknownCheck = (value: unknown) => { + isAssert.not.primitive(value); + // eslint-disable-next-line @typescript-eslint/no-restricted-types + expectTypeOf(value).toEqualTypeOf(); +}; + +const assertNotPrimitiveGenericCheck = (value: T) => { + isAssert.not.primitive(value); + const _: Exclude = value; +}; + +const assertNotNamedUndefinedExportCheck = (value: 0 | false | '' | Null | undefined | 'ok') => { + assertNotUndefined(value); + expectTypeOf(value).toEqualTypeOf<0 | false | '' | Null | 'ok'>(); +}; + +const assertNotNamedNullOrUndefinedUnknownExportCheck = (value: unknown) => { + assertNotNullOrUndefined(value); + expectTypeOf(value).toEqualTypeOf>(); +}; + +const assertNotNamedStringExportCheck = (value: string | number) => { + assertNotString(value); + expectTypeOf(value).toEqualTypeOf(); +}; + +const assertNotNamedStringUnknownExportCheck = (value: unknown) => { + assertNotString(value); + expectTypeOf(value).toEqualTypeOf>(); +}; + +const assertNotNamedPrimitiveUnknownExportCheck = (value: unknown) => { + assertNotPrimitive(value); + // eslint-disable-next-line @typescript-eslint/no-restricted-types + expectTypeOf(value).toEqualTypeOf(); +}; + +const assertNotCallableDoesNotExistCheck = (value: string | undefined) => { + // @ts-expect-error -- Generic negative assertions cannot safely infer complement types from arbitrary predicates. + isAssert.not(is.undefined, value); + const _: string | undefined = value; +}; + +const assertNotNumberDoesNotExistCheck = (value: string | number) => { + // @ts-expect-error -- `is.number` rejects `NaN`, so a narrowing negative assertion would be unsound. + isAssert.not.number(value); // eslint-disable-line @typescript-eslint/no-unsafe-call + const _: string | number = value; +}; + +const assertNotIntegerDoesNotExistCheck = (value: string | number) => { + // @ts-expect-error -- Numeric refinements are intentionally excluded from `assert.not`. + isAssert.not.integer(value); // eslint-disable-line @typescript-eslint/no-unsafe-call + const _: string | number = value; +}; + +const assertNotObjectDoesNotExistCheck = (value: Record | string) => { + // @ts-expect-error -- TypeScript's `{}` type includes primitives, so `not.object` cannot safely narrow every object-like input. + isAssert.not.object(value); // eslint-disable-line @typescript-eslint/no-unsafe-call + const _: Record | string = value; +}; + +const assertNotBlobDoesNotExistCheck = (value: Blob | File | string) => { + // @ts-expect-error -- `File` extends `Blob` in TypeScript but does not match the exact runtime `Blob` check. + isAssert.not.blob(value); // eslint-disable-line @typescript-eslint/no-unsafe-call + const _: Blob | File | string = value; +}; + +const assertNotMapDoesNotExistCheck = (value: Map | string) => { + // @ts-expect-error -- Structural object types such as `Map` can be assignable in TypeScript without matching the runtime brand check. + isAssert.not.map(value); // eslint-disable-line @typescript-eslint/no-unsafe-call, unicorn/no-array-callback-reference + const _: Map | string = value; +}; + +const assertNotSetDoesNotExistCheck = (value: Set | string) => { + // @ts-expect-error -- Structural object types such as `Set` can be assignable in TypeScript without matching the runtime brand check. + isAssert.not.set(value); // eslint-disable-line @typescript-eslint/no-unsafe-call + const _: Set | string = value; +}; + +const assertNotDateDoesNotExistCheck = (value: Date | string) => { + // @ts-expect-error -- Structural object types such as `Date` can be assignable in TypeScript without matching the runtime brand check. + isAssert.not.date(value); // eslint-disable-line @typescript-eslint/no-unsafe-call + const _: Date | string = value; +}; + +// Suppress unused variable warnings +nanCheck(42); +finiteNumberCheck(42); +nonNegativeNumberCheck(42); +positiveIntegerCheck(42); +negativeIntegerCheck(-1); +nonNegativeIntegerCheck(0); +infiniteCheck(Number.POSITIVE_INFINITY); +integerCheck(1); +safeIntegerCheck(1); +evenIntegerCheck(2); +oddIntegerCheck(1); +positiveNumberCheck(1); +negativeNumberCheck(-1); +validLengthCheck(0); +integerUnknownCheck(1); +positiveIntegerUnknownCheck(1); +integerMixedUnionCheck(1); +positiveNumberMixedUnionCheck(1); +chainedNumericGuardCheck(1); +distinctNumericBrandsStayDistinct(42 as PositiveInteger, -1 as NegativeInteger, 0 as ValidLength); +assertNotUndefinedCheck('🦄'); +assertNotUndefinedUnknownCheck('🦄'); +assertNotUndefinedGenericCheck('🦄'); +assertNotNullUnknownCheck('🦄'); +assertNotNullOrUndefinedCheck('🦄'); +assertNotNullOrUndefinedUnknownCheck('🦄'); +assertNotStringCheck(1); +assertNotStringUnknownCheck(1); +assertNotStringGenericCheck(1); +assertNotBooleanUnknownCheck(1); +assertNotSymbolUnknownCheck(1); +assertNotBigintUnknownCheck(1); +assertNotPrimitiveUnknownCheck({}); +assertNotPrimitiveGenericCheck({unicorn: true}); +assertNotNamedUndefinedExportCheck(0); +assertNotNamedNullOrUndefinedUnknownExportCheck('🦄'); +assertNotNamedStringExportCheck(1); +assertNotNamedStringUnknownExportCheck(1); +assertNotNamedPrimitiveUnknownExportCheck({}); +assertNotCallableDoesNotExistCheck('🦄'); +assertNotNumberDoesNotExistCheck(Number.NaN); +assertNotIntegerDoesNotExistCheck(1.5); +assertNotObjectDoesNotExistCheck('🦄'); +assertNotBlobDoesNotExistCheck('🦄'); +assertNotMapDoesNotExistCheck('🦄'); +assertNotSetDoesNotExistCheck('🦄'); +assertNotDateDoesNotExistCheck('🦄'); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..46013a6 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "@sindresorhus/tsconfig", + "compilerOptions": { + "types": ["node"], + "rootDir": "source", + "allowImportingTsExtensions": true, + "rewriteRelativeImportExtensions": true + }, + "include": [ + "source" + ], +}