From ba3114f89f4efaf025d8208c9e94bcdc5a56f3c4 Mon Sep 17 00:00:00 2001 From: Nicholas Berlette Date: Sat, 19 Apr 2025 17:02:31 +0000 Subject: [PATCH 01/24] config: add Dockerfile --- .devcontainer/Dockerfile | 48 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 .devcontainer/Dockerfile diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000..c555c6c --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,48 @@ +ARG VARIANT=bullseye +ARG PLATFORM=linux/amd64 +FROM --platform=${PLATFORM} mcr.microsoft.com/vscode/devcontainers/base:0-${VARIANT} + +# update system packages and cleanup cache +ARG DEBIAN_FRONTEND=noninteractive + +ARG USER=vscode +ARG HOME=/home/${USER} + +# Install cmake +RUN sudo apt-get update \ + && sudo apt-get install -y --no-install-recommends gcc \ + && sudo apt-get -y upgrade \ + && sudo rm -rf /var/lib/apt/lists/* + +ARG BASH_RC=${HOME}/.bashrc + +# deno runtime (https://deno.com) +ARG DENO_INSTALL=${HOME}/.deno +# bun package manager (https://bun.sh) +ARG BUN_INSTALL=${HOME}/.bun +# starship terminal prompt (https://starship.rs) +ARG STARSHIP_RC=${HOME}/.config/starship.toml +ARG STARSHIP_PRESET="pastel-powerline" + +# install the latest version of deno +# https://docs.deno.com/runtime/getting_started/installation +RUN /bin/bash -c "$(curl -fsSL https://deno.land/install.sh)" \ + && chown ${USER} ${DENO_INSTALL} + +RUN /bin/bash -c "$(curl -fsSL https://bun.sh/install)" \ + && chown ${USER} ${BUN_INSTALL} + +# add a couple things to bashrc +RUN echo '[[ ":$PATH:" == *":$HOMEBREW_PREFIX/bin:"* ]] || export PATH="$HOMEBREW_PREFIX/bin:$PATH";' >> ${BASH_RC} \ + && echo 'eval "$(brew shellenv)";' >> ${BASH_RC} \ + && echo 'sudo chown -R '${USER}' '${HOME}';' >> ${BASH_RC} \ + && echo 'export DENO_INSTALL="'${DENO_INSTALL}'";' >> ${BASH_RC} \ + && echo '[[ ":$PATH:" == *":$DENO_INSTALL/bin:"* ]] || export PATH="$DENO_INSTALL/bin:$PATH";' >> ${BASH_RC} \ + && echo 'command -v starship &>/dev/null || ( echo "‼️ starship not found, installing starship..." && brew install starship 2>/dev/null );' >> ${BASH_RC} \ + && echo 'command -v deno &>/dev/null || ( echo "‼️ deno not found, installing deno..." && curl -fsSL https://deno.land/install.sh | bash );' >> ${BASH_RC} \ + && echo 'command -v git-extras &>/dev/null || ( echo "‼️ git-extras not found, installing git-extras..." && brew install git-extras );' >> ${BASH_RC} \ + && echo 'sudo touch /etc/bash_completion.d/deno.bash && sudo chown '${USER}' /etc/bash_completion.d/deno.bash;' >> ${BASH_RC} \ + && echo '[ -s /etc/bash_completion.d/deno.bash ] || deno completions bash > /etc/bash_completion.d/deno.bash;' >> ${BASH_RC} \ + && echo '[ -f "'${STARSHIP_RC}'" ] || starship preset "'${STARSHIP_PRESET}'" -o "'${STARSHIP_RC}'" 2>/dev/null;' >> ${BASH_RC} \ + && echo 'eval "$(starship init bash)" 2>/dev/null;' >> ${BASH_RC} \ + && echo 'alias ll="ls -AlhFo --color=auto --si --group-directories-first --time-style=long-iso --file-type";' >> ${BASH_RC} From 0c0be532c091fd56289f64116a94d3a432667555 Mon Sep 17 00:00:00 2001 From: Nicholas Berlette Date: Sat, 19 Apr 2025 17:02:47 +0000 Subject: [PATCH 02/24] config: add devcontainer.json --- .devcontainer/devcontainer.json | 55 +++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 .devcontainer/devcontainer.json diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..b55c61f --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,55 @@ +{ + "name": "Deno", + "build": { + "dockerfile": "Dockerfile" + }, + "runArgs": ["--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined"], + "postCreateCommand": "git submodule update --init --recursive", + "containerUser": "vscode", + "remoteUser": "vscode", + // container features to add during the build step + "features": { + "git": "latest", + "sshd": "latest", + "node": "latest", + "ghcr.io/devcontainers/features/github-cli:1": {}, + "ghcr.io/meaningful-ooo/devcontainer-features/homebrew:2": {} + }, + // settings for the vscode editor + "customizations": { + "codespaces": { + // "disableAutomaticConfiguration": true, + "openFiles": [ + "README.md", + "deno.json" + ] + }, + "vscode": { + "settings": { + "deno.enable": true, + "deno.lint": true, + "deno.codeLens.test": true, + "deno.cacheOnSave": true, + "editor.tabSize": 2, + "editor.stickyTabStops": true, + "editor.linkedEditing": true, + "editor.minimap.enabled": false, + "editor.defaultFormatter": "denoland.vscode-deno", + "editor.formatOnSave": true, + "files.watcherExclude": { + "**/.coverage/**": true, + "**/docs/**": true, + "**/wiki/**": true + } + }, + "extensions": [ + "github.copilot", + "github.vscode-github-actions", + "denoland.vscode-deno", + "editorconfig.editorconfig", + "bierner.markdown-preview-github-styles", + "mutantdino.resourcemonitor" + ] + } + } +} From f17e40c026c5326391ede9a76ba60bfefff548e7 Mon Sep 17 00:00:00 2001 From: Nicholas Berlette Date: Tue, 6 May 2025 06:59:47 +0000 Subject: [PATCH 03/24] chore: update copyrights. happy cinco de mayo! --- src/_internal.ts | 2 +- src/arguments.test.ts | 6 --- src/arguments.ts | 2 +- src/array.test.ts | 5 -- src/array.ts | 18 +++---- src/array_buffer.test.ts | 6 --- src/array_buffer.ts | 2 +- src/array_buffer_like.test.ts | 6 --- src/array_buffer_like.ts | 2 +- src/array_buffer_view.test.ts | 6 --- src/array_buffer_view.ts | 2 +- src/array_iterator.test.ts | 6 --- src/array_iterator.ts | 2 +- src/array_like.test.ts | 6 --- src/array_like.ts | 3 +- src/array_like_object.test.ts | 6 --- src/array_like_object.ts | 2 +- src/async_disposable.test.ts | 6 --- src/async_disposable.ts | 2 +- src/async_function.test.ts | 6 --- src/async_function.ts | 2 +- src/async_generator.test.ts | 6 --- src/async_generator.ts | 2 +- src/async_generator_function.test.ts | 6 --- src/async_generator_function.ts | 2 +- src/async_iterable.test.ts | 6 --- src/async_iterable.ts | 2 +- src/async_iterable_iterator.test.ts | 6 --- src/async_iterable_iterator.ts | 2 +- src/async_iterable_object.test.ts | 6 --- src/async_iterable_object.ts | 2 +- src/async_iterator.test.ts | 6 --- src/async_iterator.ts | 2 +- src/bigint.test.ts | 6 --- src/bigint.ts | 2 +- src/bigint64_array.test.ts | 6 --- src/bigint64_array.ts | 2 +- src/bigint_object.test.ts | 6 --- src/bigint_object.ts | 2 +- src/biguint64_array.test.ts | 6 --- src/biguint64_array.ts | 2 +- src/boolean.test.ts | 6 --- src/boolean.ts | 2 +- src/boolean_object.test.ts | 6 --- src/boolean_object.ts | 2 +- src/both.test.ts | 6 --- src/both.ts | 2 +- src/boxed_primitive.test.ts | 6 --- src/boxed_primitive.ts | 2 +- src/buffer_source.test.ts | 6 --- src/buffer_source.ts | 2 +- src/class.test.ts | 6 --- src/class.ts | 2 +- src/closer.test.ts | 6 --- src/closer.ts | 2 +- src/constructor.ts | 4 +- src/data_view.test.ts | 6 --- src/data_view.ts | 2 +- src/date.test.ts | 6 --- src/date.ts | 2 +- src/date_string.test.ts | 6 --- src/date_string.ts | 2 +- src/defined.test.ts | 6 --- src/defined.ts | 2 +- src/disposable.test.ts | 6 --- src/disposable.ts | 2 +- src/either.test.ts | 6 --- src/either.ts | 2 +- src/empty.test.ts | 6 --- src/empty.ts | 2 +- src/empty_object.ts | 2 +- src/enum.test.ts | 6 --- src/enum.ts | 2 +- src/error.test.ts | 6 --- src/error.ts | 2 +- src/falsy.test.ts | 6 --- src/falsy.ts | 2 +- src/float16_array.test.ts | 6 --- src/float16_array.ts | 2 +- src/float32_array.test.ts | 6 --- src/float32_array.ts | 2 +- src/float64_array.test.ts | 6 --- src/float64_array.ts | 2 +- src/function.test.ts | 5 -- src/function.ts | 74 +++++++++++++++++++++++---- src/generator.test.ts | 6 --- src/generator.ts | 2 +- src/generator_function.test.ts | 6 --- src/generator_function.ts | 2 +- src/has_methods.test.ts | 5 -- src/has_methods.ts | 2 +- src/identifier.test.ts | 6 --- src/identifier.ts | 2 +- src/instance.test.ts | 6 --- src/instance.ts | 2 +- src/int16_array.test.ts | 6 --- src/int16_array.ts | 2 +- src/int32_array.test.ts | 6 --- src/int32_array.ts | 2 +- src/int8_array.test.ts | 6 --- src/int8_array.ts | 2 +- src/integer.test.ts | 6 --- src/iterable.test.ts | 6 --- src/iterable.ts | 2 +- src/iterable_iterator.test.ts | 6 --- src/iterable_iterator.ts | 2 +- src/iterable_object.test.ts | 6 --- src/iterable_object.ts | 2 +- src/iterator.test.ts | 6 --- src/iterator.ts | 2 +- src/keyof.test.ts | 6 --- src/keyof.ts | 2 +- src/map.test.ts | 6 --- src/map.ts | 2 +- src/map_iterator.test.ts | 6 --- src/map_iterator.ts | 2 +- src/map_like.test.ts | 6 --- src/map_like.ts | 2 +- src/missing.test.ts | 6 --- src/missing.ts | 2 +- src/namespace.ts | 2 +- src/non_array_object.test.ts | 5 -- src/non_array_object.ts | 2 +- src/non_empty_array.test.ts | 6 --- src/non_empty_array.ts | 3 +- src/null.test.ts | 6 --- src/null.ts | 2 +- src/number.test.ts | 6 --- src/number.ts | 2 +- src/number_object.test.ts | 6 --- src/number_object.ts | 2 +- src/object.test.ts | 6 --- src/object.ts | 2 +- src/object_like.test.ts | 6 --- src/object_like.ts | 2 +- src/plain_object.test.ts | 6 --- src/plain_object.ts | 2 +- src/present.test.ts | 6 --- src/present.ts | 2 +- src/primitive.test.ts | 6 --- src/primitive.ts | 2 +- src/printable.test.ts | 6 --- src/printable.ts | 2 +- src/promise.test.ts | 6 --- src/promise.ts | 2 +- src/promise_like.test.ts | 6 --- src/promise_like.ts | 2 +- src/property_key.test.ts | 6 --- src/property_key.ts | 2 +- src/readable_stream.test.ts | 6 --- src/readable_stream.ts | 2 +- src/reader.test.ts | 6 --- src/reader.ts | 2 +- src/reader_sync.test.ts | 6 --- src/reader_sync.ts | 2 +- src/regexp.test.ts | 6 --- src/regexp.ts | 2 +- src/registered_symbol.test.ts | 6 --- src/registered_symbol.ts | 2 +- src/semver.ts | 2 +- src/set.test.ts | 6 --- src/set.ts | 2 +- src/set_iterator.test.ts | 6 --- src/set_iterator.ts | 2 +- src/set_like.test.ts | 6 --- src/set_like.ts | 2 +- src/shared_array_buffer.test.ts | 6 --- src/shared_array_buffer.ts | 2 +- src/string.test.ts | 6 --- src/string.ts | 2 +- src/string_iterator.test.ts | 6 --- src/string_iterator.ts | 37 ++++++++++---- src/string_object.test.ts | 6 --- src/string_object.ts | 2 +- src/symbol.test.ts | 6 --- src/symbol.ts | 2 +- src/symbol_object.test.ts | 6 --- src/symbol_object.ts | 2 +- src/tagged.test.ts | 6 --- src/tagged.ts | 2 +- src/template_object.test.ts | 6 --- src/template_object.ts | 2 +- src/template_strings_array.test.ts | 6 --- src/template_strings_array.ts | 2 +- src/truthy.ts | 2 +- src/typed_array.test.ts | 6 --- src/typed_array.ts | 2 +- src/types.ts | 2 +- src/uint16_array.test.ts | 6 --- src/uint16_array.ts | 2 +- src/uint32_array.test.ts | 6 --- src/uint32_array.ts | 2 +- src/uint8_array.test.ts | 6 --- src/uint8_array.ts | 2 +- src/uint8_clamped_array.test.ts | 6 --- src/uint8_clamped_array.ts | 2 +- src/undefined.test.ts | 6 --- src/undefined.ts | 2 +- src/unique_symbol.test.ts | 6 --- src/unique_symbol.ts | 2 +- src/url.test.ts | 6 --- src/url.ts | 2 +- src/url_search_params.test.ts | 6 --- src/url_search_params.ts | 2 +- src/url_string.test.ts | 6 --- src/url_string.ts | 2 +- src/url_string_no_url_support.test.ts | 6 --- src/weak_key.test.ts | 6 --- src/weak_key.ts | 2 +- src/weak_map.test.ts | 6 --- src/weak_map.ts | 2 +- src/weak_ref.test.ts | 6 --- src/weak_ref.ts | 7 +-- src/weak_set.test.ts | 6 --- src/weak_set.ts | 2 +- src/well_known_symbol.test.ts | 6 --- src/well_known_symbol.ts | 2 +- src/whitespace.test.ts | 5 -- src/whitespace.ts | 2 +- src/writable_stream.test.ts | 6 --- src/writable_stream.ts | 2 +- src/writer.test.ts | 6 --- src/writer.ts | 2 +- src/writer_sync.test.ts | 6 --- src/writer_sync.ts | 2 +- 225 files changed, 219 insertions(+), 798 deletions(-) diff --git a/src/_internal.ts b/src/_internal.ts index 2bdeb9c..33db603 100644 --- a/src/_internal.ts +++ b/src/_internal.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/_internal + * @see https://jsr.io/@nick/is/doc/_internal */ export * from "./_internal/expect_type.ts"; diff --git a/src/arguments.test.ts b/src/arguments.test.ts index da129dd..6bde16b 100644 --- a/src/arguments.test.ts +++ b/src/arguments.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/arguments - */ - // File: ./arguments.test.ts import { assertEquals } from "@std/assert"; import isArguments from "./arguments.ts"; diff --git a/src/arguments.ts b/src/arguments.ts index f8e59dc..22fe7f1 100644 --- a/src/arguments.ts +++ b/src/arguments.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/arguments + * @see https://jsr.io/@nick/is/doc/arguments */ /** diff --git a/src/array.test.ts b/src/array.test.ts index 178b79a..3034b5a 100644 --- a/src/array.test.ts +++ b/src/array.test.ts @@ -1,8 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array - */ import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; import type { Predicate } from "@nick/is/type/predicate"; diff --git a/src/array.ts b/src/array.ts index b43cd22..509014d 100644 --- a/src/array.ts +++ b/src/array.ts @@ -1,13 +1,13 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array + * @see https://jsr.io/@nick/is/doc/array */ /** * Checks if the given value is an array. If the `Array.isArray` method is * available in the global scope, it will be used under the hood. Otherwise, - * a custom implementation will be used. + * a custom implementation is used. * * To constrain the types of each eleemnt in the array, a custom type guard * can be provided for the second argument, `test`, which will be used to @@ -46,17 +46,17 @@ import { isTaggedNative } from "./_internal.ts"; import type { Predicate } from "./type/predicate.ts"; -const ArrayIsArray: (x: unknown) => x is unknown[] = (() => { +const ArrayIsArray: (x: unknown) => x is T[] = (() => { if (typeof globalThis.Array.isArray === "function") { return globalThis.Array.isArray.bind(globalThis.Array); } // fallback checks for the native `Array` tag (e.g. it _appears_ to have a // Symbol.toStringTag when passed to Object.prototype.toString, but does not // actually have that property anywhere in its prototype chain) - return (x): x is unknown[] => ( + return (x) => ( typeof x === "object" && x !== null && isTaggedNative(x, "Array") ); -})(); +})() as (x: unknown) => x is T[]; /** * Checks if the given value is an array, optionally verifying that each of its @@ -89,11 +89,11 @@ const ArrayIsArray: (x: unknown) => x is unknown[] = (() => { * ``` * @category Indexed Collections */ -export function isArray(a: unknown, test?: Predicate): a is T[] { - if (ArrayIsArray(a)) { +export function isArray(it: unknown, test?: Predicate): it is T[] { + if (ArrayIsArray(it)) { if (typeof test === "function") { - for (let i = 0; i < a.length; i++) { - if (!test(a[i])) return false; + for (let i = 0; i < it.length; i++) { + if (!test(it[i])) return false; } } return true; diff --git a/src/array_buffer.test.ts b/src/array_buffer.test.ts index 680cc76..e51cf16 100644 --- a/src/array_buffer.test.ts +++ b/src/array_buffer.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array-buffer - */ - import { assertEquals } from "@std/assert"; import isArrayBuffer from "./array_buffer.ts"; diff --git a/src/array_buffer.ts b/src/array_buffer.ts index 0237dd7..6451894 100644 --- a/src/array_buffer.ts +++ b/src/array_buffer.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array-buffer + * @see https://jsr.io/@nick/is/doc/array-buffer */ /** diff --git a/src/array_buffer_like.test.ts b/src/array_buffer_like.test.ts index 9e3af1a..c4ebda3 100644 --- a/src/array_buffer_like.test.ts +++ b/src/array_buffer_like.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array-buffer-like - */ - import { assertEquals } from "@std/assert"; import isArrayBufferLike from "./array_buffer_like.ts"; diff --git a/src/array_buffer_like.ts b/src/array_buffer_like.ts index cf956ce..5b29924 100644 --- a/src/array_buffer_like.ts +++ b/src/array_buffer_like.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array-buffer-like + * @see https://jsr.io/@nick/is/doc/array-buffer-like */ /** diff --git a/src/array_buffer_view.test.ts b/src/array_buffer_view.test.ts index 698dbdf..27630bb 100644 --- a/src/array_buffer_view.test.ts +++ b/src/array_buffer_view.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array-buffer-view - */ - import { assertEquals } from "@std/assert"; import { isArrayBufferView } from "./array_buffer_view.ts"; diff --git a/src/array_buffer_view.ts b/src/array_buffer_view.ts index 4cfcd8e..4e32499 100644 --- a/src/array_buffer_view.ts +++ b/src/array_buffer_view.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array-buffer-view + * @see https://jsr.io/@nick/is/doc/array-buffer-view */ /** diff --git a/src/array_iterator.test.ts b/src/array_iterator.test.ts index 29d4441..70d271a 100644 --- a/src/array_iterator.test.ts +++ b/src/array_iterator.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array-iterator - */ - import { assertEquals } from "@std/assert"; import isArrayIterator from "./array_iterator.ts"; diff --git a/src/array_iterator.ts b/src/array_iterator.ts index 2075bd5..1406e2b 100644 --- a/src/array_iterator.ts +++ b/src/array_iterator.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array-iterator + * @see https://jsr.io/@nick/is/doc/array-iterator */ import { isIterator } from "./iterator.ts"; diff --git a/src/array_like.test.ts b/src/array_like.test.ts index c567815..2f7d138 100644 --- a/src/array_like.test.ts +++ b/src/array_like.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array-like - */ - import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; import { isArrayLike } from "./array_like.ts"; diff --git a/src/array_like.ts b/src/array_like.ts index 972c670..fcd6f00 100644 --- a/src/array_like.ts +++ b/src/array_like.ts @@ -1,8 +1,9 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array-like + * @see https://jsr.io/@nick/is/doc/array-like */ + import { isInteger } from "./number/integer.ts"; /** diff --git a/src/array_like_object.test.ts b/src/array_like_object.test.ts index c5295d6..23fd9d0 100644 --- a/src/array_like_object.test.ts +++ b/src/array_like_object.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array-like-object - */ - import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; import { isArrayLikeObject } from "./array_like_object.ts"; diff --git a/src/array_like_object.ts b/src/array_like_object.ts index 05b278a..8dc9702 100644 --- a/src/array_like_object.ts +++ b/src/array_like_object.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/array-like-object + * @see https://jsr.io/@nick/is/doc/array-like-object */ /** diff --git a/src/async_disposable.test.ts b/src/async_disposable.test.ts index c10fd60..7201ce9 100644 --- a/src/async_disposable.test.ts +++ b/src/async_disposable.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-disposable - */ - import { assert } from "@std/assert/assert"; import { expectType } from "./_internal.ts"; diff --git a/src/async_disposable.ts b/src/async_disposable.ts index 69e2fea..02b07ec 100644 --- a/src/async_disposable.ts +++ b/src/async_disposable.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-disposable + * @see https://jsr.io/@nick/is/doc/async-disposable */ /** diff --git a/src/async_function.test.ts b/src/async_function.test.ts index 0db8b3a..8c12cb0 100644 --- a/src/async_function.test.ts +++ b/src/async_function.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-function - */ - import { isAsyncFunction } from "./async_function.ts"; import { assert } from "@std/assert"; diff --git a/src/async_function.ts b/src/async_function.ts index fe0e64d..5e62855 100644 --- a/src/async_function.ts +++ b/src/async_function.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-function + * @see https://jsr.io/@nick/is/doc/async-function */ /** diff --git a/src/async_generator.test.ts b/src/async_generator.test.ts index f624c22..8b5ea36 100644 --- a/src/async_generator.test.ts +++ b/src/async_generator.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-generator - */ - import { assertEquals } from "@std/assert"; import { isAsyncGenerator } from "./async_generator.ts"; diff --git a/src/async_generator.ts b/src/async_generator.ts index e373d81..ecd6d19 100644 --- a/src/async_generator.ts +++ b/src/async_generator.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-generator + * @see https://jsr.io/@nick/is/doc/async-generator */ import { isAsyncIterableIterator } from "./async_iterable_iterator.ts"; diff --git a/src/async_generator_function.test.ts b/src/async_generator_function.test.ts index ae09419..5528039 100644 --- a/src/async_generator_function.test.ts +++ b/src/async_generator_function.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-generator-function - */ - import { assertEquals } from "@std/assert"; import isAsyncGeneratorFunction from "./async_generator_function.ts"; diff --git a/src/async_generator_function.ts b/src/async_generator_function.ts index c7e1a0e..7e51550 100644 --- a/src/async_generator_function.ts +++ b/src/async_generator_function.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-generator-function + * @see https://jsr.io/@nick/is/doc/async-generator-function */ import { isTagged } from "./tagged.ts"; diff --git a/src/async_iterable.test.ts b/src/async_iterable.test.ts index b746825..3c9a76d 100644 --- a/src/async_iterable.test.ts +++ b/src/async_iterable.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-iterable - */ - import { assertEquals } from "@std/assert"; import isAsyncIterable from "./async_iterable.ts"; diff --git a/src/async_iterable.ts b/src/async_iterable.ts index b29db23..0094406 100644 --- a/src/async_iterable.ts +++ b/src/async_iterable.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-iterable + * @see https://jsr.io/@nick/is/doc/async-iterable */ /** diff --git a/src/async_iterable_iterator.test.ts b/src/async_iterable_iterator.test.ts index 80626e7..65b6117 100644 --- a/src/async_iterable_iterator.test.ts +++ b/src/async_iterable_iterator.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-iterable-iterator - */ - import { assertEquals } from "@std/assert"; import isAsyncIterableIterator from "./async_iterable_iterator.ts"; diff --git a/src/async_iterable_iterator.ts b/src/async_iterable_iterator.ts index 26864ed..6ea22e1 100644 --- a/src/async_iterable_iterator.ts +++ b/src/async_iterable_iterator.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-iterable-iterator + * @see https://jsr.io/@nick/is/doc/async-iterable-iterator */ import { isAsyncIterable } from "./async_iterable.ts"; diff --git a/src/async_iterable_object.test.ts b/src/async_iterable_object.test.ts index f5b1284..170981c 100644 --- a/src/async_iterable_object.test.ts +++ b/src/async_iterable_object.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-iterable-object - */ - import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; diff --git a/src/async_iterable_object.ts b/src/async_iterable_object.ts index 029c5e0..b795f7f 100644 --- a/src/async_iterable_object.ts +++ b/src/async_iterable_object.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-iterable-object + * @see https://jsr.io/@nick/is/doc/async-iterable-object */ import { isObjectLike } from "./object_like.ts"; diff --git a/src/async_iterator.test.ts b/src/async_iterator.test.ts index 15ca2f7..e11044d 100644 --- a/src/async_iterator.test.ts +++ b/src/async_iterator.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-iterator - */ - import { assertEquals } from "@std/assert"; import isAsyncIterator from "./async_iterator.ts"; diff --git a/src/async_iterator.ts b/src/async_iterator.ts index 51d21aa..750b441 100644 --- a/src/async_iterator.ts +++ b/src/async_iterator.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/async-iterator + * @see https://jsr.io/@nick/is/doc/async-iterator */ /** diff --git a/src/bigint.test.ts b/src/bigint.test.ts index 57d2a27..6772ef2 100644 --- a/src/bigint.test.ts +++ b/src/bigint.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/bigint - */ - import { assertEquals } from "@std/assert"; import { isBigInt } from "./bigint.ts"; diff --git a/src/bigint.ts b/src/bigint.ts index 015378a..8628f82 100644 --- a/src/bigint.ts +++ b/src/bigint.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/bigint + * @see https://jsr.io/@nick/is/doc/bigint */ /** diff --git a/src/bigint64_array.test.ts b/src/bigint64_array.test.ts index 3137a49..831d938 100644 --- a/src/bigint64_array.test.ts +++ b/src/bigint64_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/bigint64-array - */ - import { assertEquals } from "@std/assert"; import { isBigInt64Array } from "./bigint64_array.ts"; diff --git a/src/bigint64_array.ts b/src/bigint64_array.ts index 17e3a8c..c52f47f 100644 --- a/src/bigint64_array.ts +++ b/src/bigint64_array.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/bigint64-array + * @see https://jsr.io/@nick/is/doc/bigint64-array */ import { isTypedArray } from "./typed_array.ts"; diff --git a/src/bigint_object.test.ts b/src/bigint_object.test.ts index 6aa2095..5f5d303 100644 --- a/src/bigint_object.test.ts +++ b/src/bigint_object.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/bigint-object - */ - import { assertEquals } from "@std/assert/equals"; import { isBigIntObject } from "./bigint_object.ts"; import { expectType } from "./_internal.ts"; diff --git a/src/bigint_object.ts b/src/bigint_object.ts index 7c99b15..4c9466f 100644 --- a/src/bigint_object.ts +++ b/src/bigint_object.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/bigint-object + * @see https://jsr.io/@nick/is/doc/bigint-object */ /** diff --git a/src/biguint64_array.test.ts b/src/biguint64_array.test.ts index 2e3f892..a3e8e08 100644 --- a/src/biguint64_array.test.ts +++ b/src/biguint64_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/biguint64-array - */ - import { assertEquals } from "@std/assert"; import { isBigUint64Array } from "./biguint64_array.ts"; diff --git a/src/biguint64_array.ts b/src/biguint64_array.ts index 2c48270..cac8c98 100644 --- a/src/biguint64_array.ts +++ b/src/biguint64_array.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/biguint64-array + * @see https://jsr.io/@nick/is/doc/biguint64-array */ import { isTypedArray } from "./typed_array.ts"; diff --git a/src/boolean.test.ts b/src/boolean.test.ts index 7d5ae5c..adfc44b 100644 --- a/src/boolean.test.ts +++ b/src/boolean.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/boolean - */ - import { assertEquals } from "@std/assert"; import { isBoolean } from "./boolean.ts"; diff --git a/src/boolean.ts b/src/boolean.ts index 035d49c..0a73143 100644 --- a/src/boolean.ts +++ b/src/boolean.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/boolean + * @see https://jsr.io/@nick/is/doc/boolean */ import { tryValueOf } from "./_internal.ts"; diff --git a/src/boolean_object.test.ts b/src/boolean_object.test.ts index 2e47048..c598838 100644 --- a/src/boolean_object.test.ts +++ b/src/boolean_object.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/boolean-object - */ - import { assertEquals } from "@std/assert/equals"; import { isBooleanObject } from "./boolean_object.ts"; import { expectType } from "./_internal.ts"; diff --git a/src/boolean_object.ts b/src/boolean_object.ts index 10c323d..0f5bea9 100644 --- a/src/boolean_object.ts +++ b/src/boolean_object.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/boolean-object + * @see https://jsr.io/@nick/is/doc/boolean-object */ /** diff --git a/src/both.test.ts b/src/both.test.ts index d2115bb..debdd2e 100644 --- a/src/both.test.ts +++ b/src/both.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/both - */ - import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; diff --git a/src/both.ts b/src/both.ts index 9600da9..a1f1efe 100644 --- a/src/both.ts +++ b/src/both.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/both + * @see https://jsr.io/@nick/is/doc/both */ /** diff --git a/src/boxed_primitive.test.ts b/src/boxed_primitive.test.ts index 68dca54..a454958 100644 --- a/src/boxed_primitive.test.ts +++ b/src/boxed_primitive.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/boxed-primitive - */ - import { assertEquals } from "@std/assert/equals"; import { type BoxedPrimitive, isBoxedPrimitive } from "./boxed_primitive.ts"; import { expectType } from "./_internal.ts"; diff --git a/src/boxed_primitive.ts b/src/boxed_primitive.ts index b33c66c..236834a 100644 --- a/src/boxed_primitive.ts +++ b/src/boxed_primitive.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/boxed-primitive + * @see https://jsr.io/@nick/is/doc/boxed-primitive */ /** diff --git a/src/buffer_source.test.ts b/src/buffer_source.test.ts index 870129f..cfcd9ae 100644 --- a/src/buffer_source.test.ts +++ b/src/buffer_source.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/buffer-source - */ - import { assertEquals } from "@std/assert"; import isBufferSource from "./buffer_source.ts"; diff --git a/src/buffer_source.ts b/src/buffer_source.ts index 38f78ee..8165d83 100644 --- a/src/buffer_source.ts +++ b/src/buffer_source.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/buffer-source + * @see https://jsr.io/@nick/is/doc/buffer-source */ import { isArrayBufferView } from "./array_buffer_view.ts"; diff --git a/src/class.test.ts b/src/class.test.ts index 9ee214a..a681011 100644 --- a/src/class.test.ts +++ b/src/class.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/class - */ - import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; diff --git a/src/class.ts b/src/class.ts index ba4c4db..ae7e08f 100644 --- a/src/class.ts +++ b/src/class.ts @@ -2,7 +2,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/class + * @see https://jsr.io/@nick/is/doc/class */ import type { Is } from "./_internal.ts"; diff --git a/src/closer.test.ts b/src/closer.test.ts index 81433d4..83b98ac 100644 --- a/src/closer.test.ts +++ b/src/closer.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/closer - */ - import { assertEquals } from "@std/assert"; import { isCloser } from "./closer.ts"; diff --git a/src/closer.ts b/src/closer.ts index 52210d8..9b23f32 100644 --- a/src/closer.ts +++ b/src/closer.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/closer + * @see https://jsr.io/@nick/is/doc/closer */ /** diff --git a/src/constructor.ts b/src/constructor.ts index 17ab5c2..145425c 100644 --- a/src/constructor.ts +++ b/src/constructor.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/constructor + * @see https://jsr.io/@nick/is/doc/constructor + * @license MIT */ /** diff --git a/src/data_view.test.ts b/src/data_view.test.ts index 5321448..60d3791 100644 --- a/src/data_view.test.ts +++ b/src/data_view.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/data-view - */ - import { assertEquals } from "@std/assert"; import isDataView from "./data_view.ts"; diff --git a/src/data_view.ts b/src/data_view.ts index 7cc310a..ebdeb08 100644 --- a/src/data_view.ts +++ b/src/data_view.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/data-view + * @see https://jsr.io/@nick/is/doc/data-view */ /** diff --git a/src/date.test.ts b/src/date.test.ts index 73450c0..01bd761 100644 --- a/src/date.test.ts +++ b/src/date.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/date - */ - import { assertEquals } from "@std/assert"; import isDate from "./date.ts"; diff --git a/src/date.ts b/src/date.ts index 2b5c203..e35d471 100644 --- a/src/date.ts +++ b/src/date.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/date + * @see https://jsr.io/@nick/is/doc/date */ /** diff --git a/src/date_string.test.ts b/src/date_string.test.ts index 9dea4bb..3fc10ff 100644 --- a/src/date_string.test.ts +++ b/src/date_string.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/date-string - */ - import { assert, assertEquals } from "@std/assert"; import { expectType } from "./_internal.ts"; import { type DateString, isDateString } from "./date_string.ts"; diff --git a/src/date_string.ts b/src/date_string.ts index a2af713..c1cea52 100644 --- a/src/date_string.ts +++ b/src/date_string.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/date-string + * @see https://jsr.io/@nick/is/doc/date-string */ /** diff --git a/src/defined.test.ts b/src/defined.test.ts index 6d83a66..c452f47 100644 --- a/src/defined.test.ts +++ b/src/defined.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/defined - */ - import { assertEquals } from "@std/assert"; import isDefined from "./defined.ts"; diff --git a/src/defined.ts b/src/defined.ts index 700506e..45d919a 100644 --- a/src/defined.ts +++ b/src/defined.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/defined + * @see https://jsr.io/@nick/is/doc/defined */ /** diff --git a/src/disposable.test.ts b/src/disposable.test.ts index a24d5d5..c4463ec 100644 --- a/src/disposable.test.ts +++ b/src/disposable.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/disposable - */ - import { assert } from "@std/assert/assert"; import { expectType } from "./_internal.ts"; diff --git a/src/disposable.ts b/src/disposable.ts index b092fb0..ccde213 100644 --- a/src/disposable.ts +++ b/src/disposable.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/disposable + * @see https://jsr.io/@nick/is/doc/disposable */ /** diff --git a/src/either.test.ts b/src/either.test.ts index fc5e2fa..f92e682 100644 --- a/src/either.test.ts +++ b/src/either.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/either - */ - import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; diff --git a/src/either.ts b/src/either.ts index 20e65ab..660f45e 100644 --- a/src/either.ts +++ b/src/either.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/either + * @see https://jsr.io/@nick/is/doc/either */ /** diff --git a/src/empty.test.ts b/src/empty.test.ts index e7c6339..3f57cfd 100644 --- a/src/empty.test.ts +++ b/src/empty.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/empty - */ - import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; diff --git a/src/empty.ts b/src/empty.ts index 23c8bf0..8fa5200 100644 --- a/src/empty.ts +++ b/src/empty.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/empty + * @see https://jsr.io/@nick/is/doc/empty */ /** diff --git a/src/empty_object.ts b/src/empty_object.ts index dc4a6e3..40cd6d9 100644 --- a/src/empty_object.ts +++ b/src/empty_object.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/empty-object + * @see https://jsr.io/@nick/is/doc/empty-object */ /** diff --git a/src/enum.test.ts b/src/enum.test.ts index 8b129b0..04b3b85 100644 --- a/src/enum.test.ts +++ b/src/enum.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/enum - */ - import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; diff --git a/src/enum.ts b/src/enum.ts index e26b374..c3806e5 100644 --- a/src/enum.ts +++ b/src/enum.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/enum + * @see https://jsr.io/@nick/is/doc/enum */ import type { unknowns } from "./_internal/types.ts"; diff --git a/src/error.test.ts b/src/error.test.ts index 88c8184..a23c89c 100644 --- a/src/error.test.ts +++ b/src/error.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/error - */ - import { assertEquals } from "@std/assert"; import { isError } from "./error.ts"; diff --git a/src/error.ts b/src/error.ts index 92931a7..7afd671 100644 --- a/src/error.ts +++ b/src/error.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/error + * @see https://jsr.io/@nick/is/doc/error */ import { isTaggedNative } from "./_internal.ts"; diff --git a/src/falsy.test.ts b/src/falsy.test.ts index aadb43b..3bb4d42 100644 --- a/src/falsy.test.ts +++ b/src/falsy.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/falsy - */ - import { assert, assertEquals } from "@std/assert"; import { type Falsy, isFalsy } from "./falsy.ts"; import { expectType } from "./_internal.ts"; diff --git a/src/falsy.ts b/src/falsy.ts index 87a0c26..c12b37f 100644 --- a/src/falsy.ts +++ b/src/falsy.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/falsy + * @see https://jsr.io/@nick/is/doc/falsy */ /** diff --git a/src/float16_array.test.ts b/src/float16_array.test.ts index 0c2b79a..651b868 100644 --- a/src/float16_array.test.ts +++ b/src/float16_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/float16-array - */ - import { assertEquals } from "@std/assert"; import { isFloat16Array } from "./float16_array.ts"; diff --git a/src/float16_array.ts b/src/float16_array.ts index b980691..118ba1e 100644 --- a/src/float16_array.ts +++ b/src/float16_array.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/float16-array + * @see https://jsr.io/@nick/is/doc/float16-array */ import { isTypedArray } from "./typed_array.ts"; diff --git a/src/float32_array.test.ts b/src/float32_array.test.ts index 961961b..51d4664 100644 --- a/src/float32_array.test.ts +++ b/src/float32_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/float32-array - */ - import { assertEquals } from "@std/assert"; import { isFloat32Array } from "./float32_array.ts"; diff --git a/src/float32_array.ts b/src/float32_array.ts index d759fca..8078c57 100644 --- a/src/float32_array.ts +++ b/src/float32_array.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/float32-array + * @see https://jsr.io/@nick/is/doc/float32-array */ import { isTypedArray } from "./typed_array.ts"; diff --git a/src/float64_array.test.ts b/src/float64_array.test.ts index 339e12e..0215d94 100644 --- a/src/float64_array.test.ts +++ b/src/float64_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/float64-array - */ - import { assertEquals } from "@std/assert"; import { isFloat64Array } from "./float64_array.ts"; diff --git a/src/float64_array.ts b/src/float64_array.ts index 3f24026..43c76be 100644 --- a/src/float64_array.ts +++ b/src/float64_array.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/float64-array + * @see https://jsr.io/@nick/is/doc/float64-array */ import { isTypedArray } from "./typed_array.ts"; diff --git a/src/function.test.ts b/src/function.test.ts index 355807b..ccd34a3 100644 --- a/src/function.test.ts +++ b/src/function.test.ts @@ -1,9 +1,4 @@ // deno-lint-ignore-file ban-types -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/function - */ import { isFunction } from "./function.ts"; import { assertEquals } from "@std/assert"; diff --git a/src/function.ts b/src/function.ts index 7ceff91..273d574 100644 --- a/src/function.ts +++ b/src/function.ts @@ -2,25 +2,79 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/function + * @see https://jsr.io/@nick/is/doc/function */ +/** + * This + * @module function + */ import type { unknowns } from "./_internal.ts"; import type { Constructor } from "./constructor.ts"; +/** + * Represents a function that takes a variable number of arguments with the + * tuple signature of type `A`, and returns a value of type `T`. + * + * This type of function does not have a specific `this` context; if you need + * to specify a custom `this` binding (e.g. for methods or functions that will + * be called via the `.call` or `.apply`), use {@linkcode ThisFn} instead. + * + * @template [T] The return type of the function. Defaults to `any`. + * @template {readonly any[]} [A=any[]] The argument type signature for the + * function, represented as a literal tuple or array. Defaults to `any[]`. + * @category Types + * @tags Function + */ export type Fn = (...args: A) => T; +/** + * Represents a function that can be called with a specific `this` context. + * + * This type is useful for defining functions that are intended to be used as + * methods of a class or object, where the `this` context is important, or + * those that are not bound to a specific context. + * + * @template [T] The type of `this` context. Defaults to `any`. + * @template {readonly any[]} [A=any[]] The argument type signature for the + * function, represented as a literal tuple or array. Defaults to `any[]`. + * @template [R] The return type of the function. Defaults to `any`. + * @category Types + * @tags Function + */ export type ThisFn< T = any, A extends readonly any[] = any[], R = any, > = (this: T, ...args: A) => R; -export type FunctionOrConstructor< +/** + * Union of all function-like types that can be used in JavaScript, including + * constructors, regular functions, and methods. This type is useful for + * defining forgiving API interfaces that can accept any function-like value. + * + * @template [T] The type of `this` context. Defaults to `any`. This is only + * relevant for the {@linkcode ThisFn} constituent type in the union; all other + * types do not use this type parameter. + * @template {readonly any[]} [A=any[]] The argument type signature for the + * function, represented as a literal tuple or array. Defaults to `any[]`. + * @template [R] The return type of the function. Defaults to `any`. This is + * used as the instance type for the {@linkcode Constructor} constituent type + * in the union. + * @category Types + * @tags Function + */ +export type FunctionLikeTypes< + T = any, + A extends readonly any[] = any[], + R = void, +> = Constructor | Fn | ThisFn; + +export type FunctionLike< T = any, A extends readonly any[] = any[], R = void, -> = Constructor | Fn | ThisFn | Function; +> = Constructor & Fn & ThisFn; /** * Check if the given value is a function. @@ -43,17 +97,17 @@ export type FunctionOrConstructor< // the 1 type parameter overload infers the type of the function from the // argument, if possible. This is useful for preserving type information about // a function signature and its arguments. -export function isFunction( +export function isFunction( it: T | unknowns, -): it is FunctionOrConstructor extends T ? Function : T; +): it is FunctionLike extends T ? Function : T; // the 2 type parameter overload allows args + return types to be specified -export function isFunction( - it: Fn | unknowns, -): it is Fn; +export function isFunction( + it: Fn | unknowns, +): it is Fn; // the 3 type parameter overload also allows the `this` type to be specified -export function isFunction( +export function isFunction( it: ThisFn | unknowns, ): it is ThisFn; @@ -63,7 +117,7 @@ export function isFunction( export function isFunction(it: unknown): it is Function; /** @internal */ -export function isFunction(it: unknown): it is FunctionOrConstructor { +export function isFunction(it: unknown): it is FunctionLike { return typeof it === "function"; } diff --git a/src/generator.test.ts b/src/generator.test.ts index e15fa8a..1142e58 100644 --- a/src/generator.test.ts +++ b/src/generator.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/generator - */ - import { assertEquals } from "@std/assert"; import { isGenerator } from "./generator.ts"; diff --git a/src/generator.ts b/src/generator.ts index 78a4e21..d405dc0 100644 --- a/src/generator.ts +++ b/src/generator.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/generator + * @see https://jsr.io/@nick/is/doc/generator */ import { isIterableIterator } from "./iterable_iterator.ts"; diff --git a/src/generator_function.test.ts b/src/generator_function.test.ts index 24e69d1..bf228cb 100644 --- a/src/generator_function.test.ts +++ b/src/generator_function.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/generator-function - */ - import { isGeneratorFunction } from "./generator_function.ts"; import { assert } from "@std/assert"; diff --git a/src/generator_function.ts b/src/generator_function.ts index 46bf80b..e033002 100644 --- a/src/generator_function.ts +++ b/src/generator_function.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/generator-function + * @see https://jsr.io/@nick/is/doc/generator-function */ import { isTagged } from "./tagged.ts"; diff --git a/src/has_methods.test.ts b/src/has_methods.test.ts index 7c01e81..7883341 100644 --- a/src/has_methods.test.ts +++ b/src/has_methods.test.ts @@ -1,8 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/has-methods - */ import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; import { hasMethods } from "./has_methods.ts"; diff --git a/src/has_methods.ts b/src/has_methods.ts index da35bfd..92ebe37 100644 --- a/src/has_methods.ts +++ b/src/has_methods.ts @@ -2,7 +2,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/has-methods + * @see https://jsr.io/@nick/is/doc/has-methods */ import { Object } from "./_internal/primordials.ts"; diff --git a/src/identifier.test.ts b/src/identifier.test.ts index 938affc..e27cd95 100644 --- a/src/identifier.test.ts +++ b/src/identifier.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/identifier - */ - import { assertEquals } from "@std/assert"; import { isIdentifier } from "./identifier.ts"; diff --git a/src/identifier.ts b/src/identifier.ts index dac2212..575f5b4 100644 --- a/src/identifier.ts +++ b/src/identifier.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/identifier + * @see https://jsr.io/@nick/is/doc/identifier */ /** diff --git a/src/instance.test.ts b/src/instance.test.ts index 2bc468b..7c24306 100644 --- a/src/instance.test.ts +++ b/src/instance.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/instance - */ - import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; diff --git a/src/instance.ts b/src/instance.ts index c4dabae..8329b38 100644 --- a/src/instance.ts +++ b/src/instance.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/instance + * @see https://jsr.io/@nick/is/doc/instance */ /** diff --git a/src/int16_array.test.ts b/src/int16_array.test.ts index c35d19a..e01e804 100644 --- a/src/int16_array.test.ts +++ b/src/int16_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/int16-array - */ - import { assertEquals } from "@std/assert"; import isInt16Array from "./int16_array.ts"; diff --git a/src/int16_array.ts b/src/int16_array.ts index bff2417..3395cc5 100644 --- a/src/int16_array.ts +++ b/src/int16_array.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/int16-array + * @see https://jsr.io/@nick/is/doc/int16-array */ import { isTypedArray } from "./typed_array.ts"; diff --git a/src/int32_array.test.ts b/src/int32_array.test.ts index 4fa55d5..4d55e50 100644 --- a/src/int32_array.test.ts +++ b/src/int32_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/int32-array - */ - import { assertEquals } from "@std/assert"; import isInt32Array from "./int32_array.ts"; diff --git a/src/int32_array.ts b/src/int32_array.ts index af46051..dda4786 100644 --- a/src/int32_array.ts +++ b/src/int32_array.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/int32-array + * @see https://jsr.io/@nick/is/doc/int32-array */ import { isTypedArray } from "./typed_array.ts"; diff --git a/src/int8_array.test.ts b/src/int8_array.test.ts index 02a4e98..1e1a8f6 100644 --- a/src/int8_array.test.ts +++ b/src/int8_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/int8-array - */ - import { assertEquals } from "@std/assert"; import isInt8Array from "./int8_array.ts"; diff --git a/src/int8_array.ts b/src/int8_array.ts index be6406f..2f45cb3 100644 --- a/src/int8_array.ts +++ b/src/int8_array.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/int8-array + * @see https://jsr.io/@nick/is/doc/int8-array */ import { isTypedArray } from "./typed_array.ts"; diff --git a/src/integer.test.ts b/src/integer.test.ts index 256c0a1..c35d3de 100644 --- a/src/integer.test.ts +++ b/src/integer.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/integer - */ - import { assertEquals } from "@std/assert"; import { isInteger, diff --git a/src/iterable.test.ts b/src/iterable.test.ts index 7985811..f4f7ef1 100644 --- a/src/iterable.test.ts +++ b/src/iterable.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/iterable - */ - import { assertEquals } from "@std/assert"; import { isIterable } from "./iterable.ts"; diff --git a/src/iterable.ts b/src/iterable.ts index 8540e53..7af84db 100644 --- a/src/iterable.ts +++ b/src/iterable.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/iterable + * @see https://jsr.io/@nick/is/doc/iterable */ /** diff --git a/src/iterable_iterator.test.ts b/src/iterable_iterator.test.ts index 299634d..45e388c 100644 --- a/src/iterable_iterator.test.ts +++ b/src/iterable_iterator.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/iterable-iterator - */ - import { assertEquals } from "@std/assert"; import { isIterableIterator } from "./iterable_iterator.ts"; diff --git a/src/iterable_iterator.ts b/src/iterable_iterator.ts index 0f8c6bd..de595e4 100644 --- a/src/iterable_iterator.ts +++ b/src/iterable_iterator.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/iterable-iterator + * @see https://jsr.io/@nick/is/doc/iterable-iterator */ import { isIterable } from "./iterable.ts"; diff --git a/src/iterable_object.test.ts b/src/iterable_object.test.ts index 58fcc11..63e5e02 100644 --- a/src/iterable_object.test.ts +++ b/src/iterable_object.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/iterable-object - */ - import { assertEquals } from "@std/assert"; import isIterableObject from "./iterable_object.ts"; diff --git a/src/iterable_object.ts b/src/iterable_object.ts index 9342367..2b11cce 100644 --- a/src/iterable_object.ts +++ b/src/iterable_object.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/iterable-object + * @see https://jsr.io/@nick/is/doc/iterable-object */ /** diff --git a/src/iterator.test.ts b/src/iterator.test.ts index fa08e97..11223eb 100644 --- a/src/iterator.test.ts +++ b/src/iterator.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/iterator - */ - import { assertEquals } from "@std/assert"; import { isIterator } from "./iterator.ts"; diff --git a/src/iterator.ts b/src/iterator.ts index 6cee9c9..2307e86 100644 --- a/src/iterator.ts +++ b/src/iterator.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/iterator + * @see https://jsr.io/@nick/is/doc/iterator */ /** diff --git a/src/keyof.test.ts b/src/keyof.test.ts index cce2f3e..3c2b9f0 100644 --- a/src/keyof.test.ts +++ b/src/keyof.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/keyof - */ - import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; diff --git a/src/keyof.ts b/src/keyof.ts index 9f9abd4..463bedc 100644 --- a/src/keyof.ts +++ b/src/keyof.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/keyof + * @see https://jsr.io/@nick/is/doc/keyof */ import { isPropertyKey } from "./property_key.ts"; diff --git a/src/map.test.ts b/src/map.test.ts index dcb9dcb..0e07a26 100644 --- a/src/map.test.ts +++ b/src/map.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/map - */ - import { assertEquals } from "@std/assert"; import isMap from "./map.ts"; diff --git a/src/map.ts b/src/map.ts index 114e9ad..b63289c 100644 --- a/src/map.ts +++ b/src/map.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/map + * @see https://jsr.io/@nick/is/doc/map */ const MapPrototypeGetSize = Object.getOwnPropertyDescriptor( diff --git a/src/map_iterator.test.ts b/src/map_iterator.test.ts index 048c3d3..3f32654 100644 --- a/src/map_iterator.test.ts +++ b/src/map_iterator.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/map-iterator - */ - import { assertEquals } from "@std/assert"; import isMapIterator from "./map_iterator.ts"; diff --git a/src/map_iterator.ts b/src/map_iterator.ts index 61a4757..2dd3495 100644 --- a/src/map_iterator.ts +++ b/src/map_iterator.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/map-iterator + * @see https://jsr.io/@nick/is/doc/map-iterator */ import { isIterator } from "./iterator.ts"; diff --git a/src/map_like.test.ts b/src/map_like.test.ts index f9a4609..2e03e89 100644 --- a/src/map_like.test.ts +++ b/src/map_like.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/map-like - */ - import { assert, assertFalse } from "@std/assert"; import { isMapLike, isMapLikeConstructor } from "./map_like.ts"; diff --git a/src/map_like.ts b/src/map_like.ts index cfaabbb..836e88c 100644 --- a/src/map_like.ts +++ b/src/map_like.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/map-like + * @see https://jsr.io/@nick/is/doc/map-like */ import { isReadonlyCollection } from "./set_like.ts"; diff --git a/src/missing.test.ts b/src/missing.test.ts index df4a391..bbd105a 100644 --- a/src/missing.test.ts +++ b/src/missing.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/missing - */ - import { assertEquals } from "@std/assert"; import { isMissing } from "./missing.ts"; diff --git a/src/missing.ts b/src/missing.ts index 25bcc62..ec7ba03 100644 --- a/src/missing.ts +++ b/src/missing.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/missing + * @see https://jsr.io/@nick/is/doc/missing */ /** diff --git a/src/namespace.ts b/src/namespace.ts index fe38f10..9ba9fa7 100644 --- a/src/namespace.ts +++ b/src/namespace.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/namespace + * @see https://jsr.io/@nick/is/doc/namespace */ /** diff --git a/src/non_array_object.test.ts b/src/non_array_object.test.ts index 9ef2879..574b267 100644 --- a/src/non_array_object.test.ts +++ b/src/non_array_object.test.ts @@ -1,8 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/non-array-object - */ import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; import { expectType } from "@nick/is/type/expect"; diff --git a/src/non_array_object.ts b/src/non_array_object.ts index 26c9674..6ae15cb 100644 --- a/src/non_array_object.ts +++ b/src/non_array_object.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/non-array-object + * @see https://jsr.io/@nick/is/doc/non-array-object */ /** diff --git a/src/non_empty_array.test.ts b/src/non_empty_array.test.ts index 46d6b01..f65880d 100644 --- a/src/non_empty_array.test.ts +++ b/src/non_empty_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/non-empty-array - */ - import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; import type { Predicate } from "@nick/is/type/predicate"; diff --git a/src/non_empty_array.ts b/src/non_empty_array.ts index 3e85040..e4bab6c 100644 --- a/src/non_empty_array.ts +++ b/src/non_empty_array.ts @@ -1,8 +1,9 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/non-empty-array + * @see https://jsr.io/@nick/is/doc/non-empty-array */ + /** * This module provides the {@linkcode isNonEmptyArray} predicate, which * checks if a given value is an array with at least one element, and diff --git a/src/null.test.ts b/src/null.test.ts index 1881d68..906c6fe 100644 --- a/src/null.test.ts +++ b/src/null.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/null - */ - import { assertEquals } from "@std/assert"; import { isNull } from "./null.ts"; diff --git a/src/null.ts b/src/null.ts index 320b3e8..e4aa3c6 100644 --- a/src/null.ts +++ b/src/null.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/null + * @see https://jsr.io/@nick/is/doc/null */ /** diff --git a/src/number.test.ts b/src/number.test.ts index 1c573a4..8ddf787 100644 --- a/src/number.test.ts +++ b/src/number.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/number - */ - import { assertEquals } from "@std/assert"; import { isNegativeNumber, diff --git a/src/number.ts b/src/number.ts index 29e0442..c912b3c 100644 --- a/src/number.ts +++ b/src/number.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/number + * @see https://jsr.io/@nick/is/doc/number */ export * from "./number/mod.ts"; diff --git a/src/number_object.test.ts b/src/number_object.test.ts index 96117b0..b7a8fcb 100644 --- a/src/number_object.test.ts +++ b/src/number_object.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/number-object - */ - import { assertEquals } from "@std/assert/equals"; import { isNumberObject } from "./number_object.ts"; import { expectType } from "./_internal.ts"; diff --git a/src/number_object.ts b/src/number_object.ts index fb128a3..96e2012 100644 --- a/src/number_object.ts +++ b/src/number_object.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/number-object + * @see https://jsr.io/@nick/is/doc/number-object */ /** diff --git a/src/object.test.ts b/src/object.test.ts index 523d937..2aa949c 100644 --- a/src/object.test.ts +++ b/src/object.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/object - */ - import { assertEquals } from "@std/assert"; import { isObject } from "./object.ts"; diff --git a/src/object.ts b/src/object.ts index f5e516f..141a1b6 100644 --- a/src/object.ts +++ b/src/object.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/object + * @see https://jsr.io/@nick/is/doc/object */ /** diff --git a/src/object_like.test.ts b/src/object_like.test.ts index bc697bd..8ced6c3 100644 --- a/src/object_like.test.ts +++ b/src/object_like.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/object-like - */ - import { isObjectLike } from "./object_like.ts"; import { assert } from "@std/assert"; diff --git a/src/object_like.ts b/src/object_like.ts index 9651f6a..5a7d5c7 100644 --- a/src/object_like.ts +++ b/src/object_like.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/object-like + * @see https://jsr.io/@nick/is/doc/object-like */ /** diff --git a/src/plain_object.test.ts b/src/plain_object.test.ts index 87bfec4..9680013 100644 --- a/src/plain_object.test.ts +++ b/src/plain_object.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/plain-object - */ - import { assertEquals } from "@std/assert"; import isPlainObject from "./plain_object.ts"; diff --git a/src/plain_object.ts b/src/plain_object.ts index 8438960..20b8da4 100644 --- a/src/plain_object.ts +++ b/src/plain_object.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/plain-object + * @see https://jsr.io/@nick/is/doc/plain-object */ import { isTaggedNative } from "./_internal.ts"; diff --git a/src/present.test.ts b/src/present.test.ts index e860cef..0646a48 100644 --- a/src/present.test.ts +++ b/src/present.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/present - */ - import { assertEquals } from "@std/assert"; import { isPresent } from "./present.ts"; diff --git a/src/present.ts b/src/present.ts index 28c3a0f..17c059e 100644 --- a/src/present.ts +++ b/src/present.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/present + * @see https://jsr.io/@nick/is/doc/present */ /** diff --git a/src/primitive.test.ts b/src/primitive.test.ts index c0c0355..aab278a 100644 --- a/src/primitive.test.ts +++ b/src/primitive.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/primitive - */ - import { isPrimitive } from "./primitive.ts"; import { assertEquals } from "@std/assert"; diff --git a/src/primitive.ts b/src/primitive.ts index 9bd889a..b223cf3 100644 --- a/src/primitive.ts +++ b/src/primitive.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/primitive + * @see https://jsr.io/@nick/is/doc/primitive */ /** diff --git a/src/printable.test.ts b/src/printable.test.ts index 13c1b11..580672f 100644 --- a/src/printable.test.ts +++ b/src/printable.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/printable - */ - import { assertEquals } from "@std/assert"; import isPrintable from "./printable.ts"; diff --git a/src/printable.ts b/src/printable.ts index 09a55f5..014ca4d 100644 --- a/src/printable.ts +++ b/src/printable.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/printable + * @see https://jsr.io/@nick/is/doc/printable */ import { isString } from "./string.ts"; diff --git a/src/promise.test.ts b/src/promise.test.ts index 95131b7..747ea29 100644 --- a/src/promise.test.ts +++ b/src/promise.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/promise - */ - import { assertEquals } from "@std/assert"; import { isPromise } from "./promise.ts"; diff --git a/src/promise.ts b/src/promise.ts index 404bddd..4ddb1db 100644 --- a/src/promise.ts +++ b/src/promise.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/promise + * @see https://jsr.io/@nick/is/doc/promise */ import { isTaggedNative } from "./_internal.ts"; diff --git a/src/promise_like.test.ts b/src/promise_like.test.ts index 121ff04..1b22f9c 100644 --- a/src/promise_like.test.ts +++ b/src/promise_like.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/promise-like - */ - import { assertEquals } from "@std/assert"; import isPromiseLike from "./promise_like.ts"; diff --git a/src/promise_like.ts b/src/promise_like.ts index 1d495cf..841ae4a 100644 --- a/src/promise_like.ts +++ b/src/promise_like.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/promise-like + * @see https://jsr.io/@nick/is/doc/promise-like */ import { isFunction } from "./function.ts"; diff --git a/src/property_key.test.ts b/src/property_key.test.ts index b2b5d5b..eff7838 100644 --- a/src/property_key.test.ts +++ b/src/property_key.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/property-key - */ - import { assertEquals } from "@std/assert"; import { isPropertyKey } from "./property_key.ts"; diff --git a/src/property_key.ts b/src/property_key.ts index 7a6e502..f4673f1 100644 --- a/src/property_key.ts +++ b/src/property_key.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/property-key + * @see https://jsr.io/@nick/is/doc/property-key */ /** diff --git a/src/readable_stream.test.ts b/src/readable_stream.test.ts index b6525e8..8e7dfbd 100644 --- a/src/readable_stream.test.ts +++ b/src/readable_stream.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/readable-stream - */ - import { assertEquals } from "@std/assert"; import { isReadableStream } from "./readable_stream.ts"; diff --git a/src/readable_stream.ts b/src/readable_stream.ts index d8b8037..cea2023 100644 --- a/src/readable_stream.ts +++ b/src/readable_stream.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/readable-stream + * @see https://jsr.io/@nick/is/doc/readable-stream */ import { isObject } from "./object.ts"; diff --git a/src/reader.test.ts b/src/reader.test.ts index 8a373c6..c143780 100644 --- a/src/reader.test.ts +++ b/src/reader.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/reader - */ - import { assertEquals } from "@std/assert"; import { isReader } from "./reader.ts"; diff --git a/src/reader.ts b/src/reader.ts index 8c7aebb..b5676e9 100644 --- a/src/reader.ts +++ b/src/reader.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/reader + * @see https://jsr.io/@nick/is/doc/reader */ /** diff --git a/src/reader_sync.test.ts b/src/reader_sync.test.ts index c72dffb..0d92686 100644 --- a/src/reader_sync.test.ts +++ b/src/reader_sync.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/reader-sync - */ - import { assertEquals } from "@std/assert"; import { isReaderSync } from "./reader_sync.ts"; diff --git a/src/reader_sync.ts b/src/reader_sync.ts index b7e6cb4..131763a 100644 --- a/src/reader_sync.ts +++ b/src/reader_sync.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/reader-sync + * @see https://jsr.io/@nick/is/doc/reader-sync */ /** diff --git a/src/regexp.test.ts b/src/regexp.test.ts index 90f1c74..85efbbe 100644 --- a/src/regexp.test.ts +++ b/src/regexp.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/regexp - */ - import { assertEquals } from "@std/assert"; import { isRegExp } from "./regexp.ts"; diff --git a/src/regexp.ts b/src/regexp.ts index cb3a4fd..7d51f71 100644 --- a/src/regexp.ts +++ b/src/regexp.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/regexp + * @see https://jsr.io/@nick/is/doc/regexp */ import { isObjectLike } from "./object_like.ts"; diff --git a/src/registered_symbol.test.ts b/src/registered_symbol.test.ts index f932404..a0cc9d9 100644 --- a/src/registered_symbol.test.ts +++ b/src/registered_symbol.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/registered-symbol - */ - import { assertEquals } from "@std/assert"; import { isRegisteredSymbol, diff --git a/src/registered_symbol.ts b/src/registered_symbol.ts index e67a87f..68384e5 100644 --- a/src/registered_symbol.ts +++ b/src/registered_symbol.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/registered-symbol + * @see https://jsr.io/@nick/is/doc/registered-symbol */ import type { Brand } from "./_internal.ts"; diff --git a/src/semver.ts b/src/semver.ts index 438f2a8..dfbfde4 100644 --- a/src/semver.ts +++ b/src/semver.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/semver + * @see https://jsr.io/@nick/is/doc/semver */ import type { Brand, Flavor } from "./_internal.ts"; diff --git a/src/set.test.ts b/src/set.test.ts index 0eb50a2..ea11721 100644 --- a/src/set.test.ts +++ b/src/set.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/set - */ - // File: ./set.test.ts import { assertEquals } from "@std/assert"; import isSet from "./set.ts"; diff --git a/src/set.ts b/src/set.ts index d292a79..bade3c1 100644 --- a/src/set.ts +++ b/src/set.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/set + * @see https://jsr.io/@nick/is/doc/set */ const SetPrototypeGetSize = Object.getOwnPropertyDescriptor( diff --git a/src/set_iterator.test.ts b/src/set_iterator.test.ts index 2947e31..ae29788 100644 --- a/src/set_iterator.test.ts +++ b/src/set_iterator.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/set-iterator - */ - // File: ./set-iterator.test.ts import { isSetIterator } from "./set_iterator.ts"; import { assertEquals } from "@std/assert"; diff --git a/src/set_iterator.ts b/src/set_iterator.ts index 3db1668..2a7faa0 100644 --- a/src/set_iterator.ts +++ b/src/set_iterator.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/set-iterator + * @see https://jsr.io/@nick/is/doc/set-iterator */ import { isIterator } from "./iterator.ts"; diff --git a/src/set_like.test.ts b/src/set_like.test.ts index 607acc8..6e6e52e 100644 --- a/src/set_like.test.ts +++ b/src/set_like.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/set-like - */ - import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; diff --git a/src/set_like.ts b/src/set_like.ts index b1c0802..5a5634d 100644 --- a/src/set_like.ts +++ b/src/set_like.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/set-like + * @see https://jsr.io/@nick/is/doc/set-like */ import { hasMethods } from "./has_methods.ts"; diff --git a/src/shared_array_buffer.test.ts b/src/shared_array_buffer.test.ts index aad2201..842221c 100644 --- a/src/shared_array_buffer.test.ts +++ b/src/shared_array_buffer.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/shared-array-buffer - */ - import { assertEquals } from "@std/assert"; import isSharedArrayBuffer from "./shared_array_buffer.ts"; diff --git a/src/shared_array_buffer.ts b/src/shared_array_buffer.ts index 3103be9..7d586f7 100644 --- a/src/shared_array_buffer.ts +++ b/src/shared_array_buffer.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/shared-array-buffer + * @see https://jsr.io/@nick/is/doc/shared-array-buffer */ import { uncurryGetter } from "./_internal.ts"; diff --git a/src/string.test.ts b/src/string.test.ts index 3882b04..2a75c4a 100644 --- a/src/string.test.ts +++ b/src/string.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/string - */ - import { isString } from "./string.ts"; import { assertEquals } from "@std/assert"; diff --git a/src/string.ts b/src/string.ts index 2d62e60..0101074 100644 --- a/src/string.ts +++ b/src/string.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/string + * @see https://jsr.io/@nick/is/doc/string */ import { tryValueOf } from "./_internal.ts"; diff --git a/src/string_iterator.test.ts b/src/string_iterator.test.ts index ba54a66..f5733f3 100644 --- a/src/string_iterator.test.ts +++ b/src/string_iterator.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/string-iterator - */ - import { assertEquals } from "@std/assert"; import { isStringIterator } from "./string_iterator.ts"; diff --git a/src/string_iterator.ts b/src/string_iterator.ts index 987d9dc..5986f24 100644 --- a/src/string_iterator.ts +++ b/src/string_iterator.ts @@ -1,12 +1,37 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/string-iterator + * @see https://jsr.io/@nick/is/doc/string-iterator + */ + +/** + * Check if the given value is a string iterator, which is an iterable iterator + * that yields individual characters from a string literal or String object. + * This is the type of object returned by `String.prototype[Symbol.iterator]`. + * + * @param it The value to check. + * @returns `true` if the value is a string iterator, `false` otherwise. + * @example + * ```ts + * import { isStringIterator } from "jsr:@nick/is/string-iterator"; + * + * const str = "foo"; + * const iter = str[Symbol.iterator](); + * console.log(isStringIterator(iterator)); // true + * console.log(isStringIterator(str)); // false + * ``` + * @category Iterables + * @module string-iterator */ import { isIterator } from "./iterator.ts"; import { isTagged } from "./tagged.ts"; -import type { Split } from "./_internal.ts"; + +/** Represents a string iterator. */ +export interface StringIterator + extends IteratorObject { + readonly [Symbol.toStringTag]: "String Iterator"; +} /** * Check if the given value is a string iterator, which is an iterable iterator @@ -25,7 +50,7 @@ import type { Split } from "./_internal.ts"; * console.log(isStringIterator(str)); // false * ``` * @category Iterables - * @module string-iterator + * @tags String, Iterator */ export function isStringIterator( it: unknown, @@ -34,9 +59,3 @@ export function isStringIterator( } export default isStringIterator; - -/** Represents a string iterator. */ -export interface StringIterator - extends IterableIterator[number]> { - readonly [Symbol.toStringTag]: "String Iterator"; -} diff --git a/src/string_object.test.ts b/src/string_object.test.ts index a8a8341..e2bbd68 100644 --- a/src/string_object.test.ts +++ b/src/string_object.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/string-object - */ - import { assertEquals } from "@std/assert/equals"; import { isStringObject } from "./string_object.ts"; import { expectType } from "./_internal.ts"; diff --git a/src/string_object.ts b/src/string_object.ts index f1f14f0..2058c77 100644 --- a/src/string_object.ts +++ b/src/string_object.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/string-object + * @see https://jsr.io/@nick/is/doc/string-object */ /** diff --git a/src/symbol.test.ts b/src/symbol.test.ts index ea07e7b..b72b9ba 100644 --- a/src/symbol.test.ts +++ b/src/symbol.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/symbol - */ - import { isSymbol } from "./symbol.ts"; import { assertEquals } from "@std/assert"; diff --git a/src/symbol.ts b/src/symbol.ts index 11af2fc..39ae80f 100644 --- a/src/symbol.ts +++ b/src/symbol.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/symbol + * @see https://jsr.io/@nick/is/doc/symbol */ import { tryValueOf } from "./_internal.ts"; diff --git a/src/symbol_object.test.ts b/src/symbol_object.test.ts index 6873ea2..575d05c 100644 --- a/src/symbol_object.test.ts +++ b/src/symbol_object.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/symbol-object - */ - import { assertEquals } from "@std/assert/equals"; import { isSymbolObject } from "./symbol_object.ts"; import { expectType } from "./_internal.ts"; diff --git a/src/symbol_object.ts b/src/symbol_object.ts index 1188686..c728d29 100644 --- a/src/symbol_object.ts +++ b/src/symbol_object.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/symbol-object + * @see https://jsr.io/@nick/is/doc/symbol-object */ /** diff --git a/src/tagged.test.ts b/src/tagged.test.ts index 27619cb..90f1a35 100644 --- a/src/tagged.test.ts +++ b/src/tagged.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/tagged - */ - import { assertEquals } from "@std/assert"; import isTagged from "./tagged.ts"; diff --git a/src/tagged.ts b/src/tagged.ts index a05d169..6209e10 100644 --- a/src/tagged.ts +++ b/src/tagged.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/tagged + * @see https://jsr.io/@nick/is/doc/tagged */ /** diff --git a/src/template_object.test.ts b/src/template_object.test.ts index 8c6baff..b697642 100644 --- a/src/template_object.test.ts +++ b/src/template_object.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/template-object - */ - import { assertEquals } from "@std/assert"; import { isTemplateObject } from "./template_object.ts"; diff --git a/src/template_object.ts b/src/template_object.ts index ee8176f..7dd60fe 100644 --- a/src/template_object.ts +++ b/src/template_object.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/template-object + * @see https://jsr.io/@nick/is/doc/template-object */ /** diff --git a/src/template_strings_array.test.ts b/src/template_strings_array.test.ts index 6275d09..822a830 100644 --- a/src/template_strings_array.test.ts +++ b/src/template_strings_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/template-strings-array - */ - import { assertEquals } from "@std/assert"; import { isTemplateStringsArray } from "./template_strings_array.ts"; diff --git a/src/template_strings_array.ts b/src/template_strings_array.ts index e6185e2..f45dac1 100644 --- a/src/template_strings_array.ts +++ b/src/template_strings_array.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/template-strings-array + * @see https://jsr.io/@nick/is/doc/template-strings-array */ /** diff --git a/src/truthy.ts b/src/truthy.ts index 8380975..b7e92a7 100644 --- a/src/truthy.ts +++ b/src/truthy.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/truthy + * @see https://jsr.io/@nick/is/doc/truthy */ import type { Falsy } from "./falsy.ts"; diff --git a/src/typed_array.test.ts b/src/typed_array.test.ts index 7ba9372..a787e9e 100644 --- a/src/typed_array.test.ts +++ b/src/typed_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/typed-array - */ - import { assertEquals } from "@std/assert"; import { isTypedArray } from "./typed_array.ts"; diff --git a/src/typed_array.ts b/src/typed_array.ts index 128102f..c7e99eb 100644 --- a/src/typed_array.ts +++ b/src/typed_array.ts @@ -2,7 +2,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/typed-array + * @see https://jsr.io/@nick/is/doc/typed-array */ import type { unknowns, ValueOf } from "./_internal/types.ts"; diff --git a/src/types.ts b/src/types.ts index d4e57b9..71df52b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/types + * @see https://jsr.io/@nick/is/doc/types */ /** diff --git a/src/uint16_array.test.ts b/src/uint16_array.test.ts index ecc5c3f..b93a298 100644 --- a/src/uint16_array.test.ts +++ b/src/uint16_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/uint16-array - */ - import { assertEquals } from "@std/assert"; import { isUint16Array } from "./uint16_array.ts"; diff --git a/src/uint16_array.ts b/src/uint16_array.ts index c7171ca..e93b93c 100644 --- a/src/uint16_array.ts +++ b/src/uint16_array.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/uint16-array + * @see https://jsr.io/@nick/is/doc/uint16-array */ import { isTypedArray } from "./typed_array.ts"; diff --git a/src/uint32_array.test.ts b/src/uint32_array.test.ts index 1944fc4..6c1da7e 100644 --- a/src/uint32_array.test.ts +++ b/src/uint32_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/uint32-array - */ - import { assertEquals } from "@std/assert"; import { isUint32Array } from "./uint32_array.ts"; diff --git a/src/uint32_array.ts b/src/uint32_array.ts index ef3d798..18bf055 100644 --- a/src/uint32_array.ts +++ b/src/uint32_array.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/uint32-array + * @see https://jsr.io/@nick/is/doc/uint32-array */ import { isTypedArray } from "./typed_array.ts"; diff --git a/src/uint8_array.test.ts b/src/uint8_array.test.ts index 507051b..4592f39 100644 --- a/src/uint8_array.test.ts +++ b/src/uint8_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/uint8-array - */ - import { assertEquals } from "@std/assert"; import { isUint8Array } from "./uint8_array.ts"; diff --git a/src/uint8_array.ts b/src/uint8_array.ts index 6409848..9f724ff 100644 --- a/src/uint8_array.ts +++ b/src/uint8_array.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/uint8-array + * @see https://jsr.io/@nick/is/doc/uint8-array */ import { isTypedArray } from "./typed_array.ts"; diff --git a/src/uint8_clamped_array.test.ts b/src/uint8_clamped_array.test.ts index 1728e73..09b3543 100644 --- a/src/uint8_clamped_array.test.ts +++ b/src/uint8_clamped_array.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/uint8-clamped-array - */ - import { assertEquals } from "@std/assert"; import { isUint8ClampedArray } from "./uint8_clamped_array.ts"; diff --git a/src/uint8_clamped_array.ts b/src/uint8_clamped_array.ts index 3f8bfaa..870fea2 100644 --- a/src/uint8_clamped_array.ts +++ b/src/uint8_clamped_array.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/uint8-clamped-array + * @see https://jsr.io/@nick/is/doc/uint8-clamped-array */ import { isTypedArray } from "./typed_array.ts"; diff --git a/src/undefined.test.ts b/src/undefined.test.ts index d04c0c3..23020ae 100644 --- a/src/undefined.test.ts +++ b/src/undefined.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/undefined - */ - import { assertEquals } from "@std/assert"; import { isUndefined } from "./undefined.ts"; diff --git a/src/undefined.ts b/src/undefined.ts index 983ba0a..c9d7cc3 100644 --- a/src/undefined.ts +++ b/src/undefined.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/undefined + * @see https://jsr.io/@nick/is/doc/undefined */ /** diff --git a/src/unique_symbol.test.ts b/src/unique_symbol.test.ts index 09c8803..3d1f46f 100644 --- a/src/unique_symbol.test.ts +++ b/src/unique_symbol.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/unique-symbol - */ - import { assertEquals } from "@std/assert"; import { isUniqueSymbol } from "./unique_symbol.ts"; diff --git a/src/unique_symbol.ts b/src/unique_symbol.ts index f3c05ae..d028d3a 100644 --- a/src/unique_symbol.ts +++ b/src/unique_symbol.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/unique-symbol + * @see https://jsr.io/@nick/is/doc/unique-symbol */ import type { Brand } from "./_internal.ts"; diff --git a/src/url.test.ts b/src/url.test.ts index 29b8205..98e86b7 100644 --- a/src/url.test.ts +++ b/src/url.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/url - */ - import { assert } from "@std/assert"; import { isURL } from "./url.ts"; diff --git a/src/url.ts b/src/url.ts index 0de467a..f3d8d59 100644 --- a/src/url.ts +++ b/src/url.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/url + * @see https://jsr.io/@nick/is/doc/url */ /** diff --git a/src/url_search_params.test.ts b/src/url_search_params.test.ts index 8befcc8..ba4c768 100644 --- a/src/url_search_params.test.ts +++ b/src/url_search_params.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/url-search-params - */ - import { assert } from "@std/assert"; import { isURLSearchParams } from "./url_search_params.ts"; diff --git a/src/url_search_params.ts b/src/url_search_params.ts index 42a4fd4..c7887a4 100644 --- a/src/url_search_params.ts +++ b/src/url_search_params.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/url-search-params + * @see https://jsr.io/@nick/is/doc/url-search-params */ /** diff --git a/src/url_string.test.ts b/src/url_string.test.ts index bad6b0b..ea1b14a 100644 --- a/src/url_string.test.ts +++ b/src/url_string.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/url-string - */ - import { assertEquals } from "@std/assert"; import { isURLString } from "./url_string.ts"; diff --git a/src/url_string.ts b/src/url_string.ts index 87b8433..1bd5040 100644 --- a/src/url_string.ts +++ b/src/url_string.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/url-string + * @see https://jsr.io/@nick/is/doc/url-string */ /** diff --git a/src/url_string_no_url_support.test.ts b/src/url_string_no_url_support.test.ts index 7e374e1..8475af1 100644 --- a/src/url_string_no_url_support.test.ts +++ b/src/url_string_no_url_support.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/url-string-no-url-support - */ - import { assertEquals } from "@std/assert/equals"; import type { URLString } from "./url_string.ts"; diff --git a/src/weak_key.test.ts b/src/weak_key.test.ts index 0ff3da3..3ef1676 100644 --- a/src/weak_key.test.ts +++ b/src/weak_key.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/weak-key - */ - import { assertEquals } from "@std/assert"; import { isWeakKey } from "./weak_key.ts"; diff --git a/src/weak_key.ts b/src/weak_key.ts index 431f367..e684065 100644 --- a/src/weak_key.ts +++ b/src/weak_key.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/weak-key + * @see https://jsr.io/@nick/is/doc/weak-key */ /** diff --git a/src/weak_map.test.ts b/src/weak_map.test.ts index c09bd24..9ef7d73 100644 --- a/src/weak_map.test.ts +++ b/src/weak_map.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/weak-map - */ - import { assertEquals } from "@std/assert"; import isWeakMap from "./weak_map.ts"; diff --git a/src/weak_map.ts b/src/weak_map.ts index ae0c8e1..63a74eb 100644 --- a/src/weak_map.ts +++ b/src/weak_map.ts @@ -2,7 +2,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/weak-map + * @see https://jsr.io/@nick/is/doc/weak-map */ /** diff --git a/src/weak_ref.test.ts b/src/weak_ref.test.ts index 423000d..0dca782 100644 --- a/src/weak_ref.test.ts +++ b/src/weak_ref.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/weak-ref - */ - // File: ./weak-ref.test.ts import { assertEquals } from "@std/assert"; import { isWeakRef } from "./weak_ref.ts"; diff --git a/src/weak_ref.ts b/src/weak_ref.ts index b313b55..d12e3d4 100644 --- a/src/weak_ref.ts +++ b/src/weak_ref.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/weak-ref + * @see https://jsr.io/@nick/is/doc/weak-ref */ /** @@ -12,6 +12,7 @@ * @module weak-ref */ import type { WeakKey } from "./weak_key.ts"; +import { WeakRefPrototypeDeref } from "./_internal/primordials.ts"; /** * Checks if {@linkcode obj} is a WeakRef. For more information on this type of @@ -46,9 +47,9 @@ export function isWeakRef( export function isWeakRef(obj: unknown): obj is WeakRef; /** @internal */ export function isWeakRef(obj: unknown): obj is WeakRef { - if (typeof globalThis.WeakRef !== "function") return false; + if (typeof WeakRef !== "function") return false; try { - globalThis.WeakRef.prototype.deref.call(obj); + WeakRefPrototypeDeref?.(obj); return true; } catch { return false; diff --git a/src/weak_set.test.ts b/src/weak_set.test.ts index 6603188..c541ed4 100644 --- a/src/weak_set.test.ts +++ b/src/weak_set.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/weak-set - */ - import { assertEquals } from "@std/assert"; import isWeakSet from "./weak_set.ts"; diff --git a/src/weak_set.ts b/src/weak_set.ts index fef4fea..aaca5f6 100644 --- a/src/weak_set.ts +++ b/src/weak_set.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/weak-set + * @see https://jsr.io/@nick/is/doc/weak-set */ /** diff --git a/src/well_known_symbol.test.ts b/src/well_known_symbol.test.ts index 687579f..9b3038b 100644 --- a/src/well_known_symbol.test.ts +++ b/src/well_known_symbol.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/well-known-symbol - */ - import { assertEquals } from "@std/assert"; import { isWellKnownSymbol } from "./well_known_symbol.ts"; diff --git a/src/well_known_symbol.ts b/src/well_known_symbol.ts index 4f06106..8f53fc8 100644 --- a/src/well_known_symbol.ts +++ b/src/well_known_symbol.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/well-known-symbol + * @see https://jsr.io/@nick/is/doc/well-known-symbol */ import type { ValueOf } from "./_internal/types.ts"; diff --git a/src/whitespace.test.ts b/src/whitespace.test.ts index c1f735c..6e36a62 100644 --- a/src/whitespace.test.ts +++ b/src/whitespace.test.ts @@ -1,8 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/whitespace - */ import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; import type { IsExact } from "@nick/is/type/exact"; diff --git a/src/whitespace.ts b/src/whitespace.ts index de29015..ac567e4 100644 --- a/src/whitespace.ts +++ b/src/whitespace.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/whitespace + * @see https://jsr.io/@nick/is/doc/whitespace */ import isIterable from "./iterable.ts"; diff --git a/src/writable_stream.test.ts b/src/writable_stream.test.ts index d987770..c741759 100644 --- a/src/writable_stream.test.ts +++ b/src/writable_stream.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/writable-stream - */ - import { assertEquals } from "@std/assert"; import { isWritableStream } from "./writable_stream.ts"; diff --git a/src/writable_stream.ts b/src/writable_stream.ts index 25bcfa7..c701c4f 100644 --- a/src/writable_stream.ts +++ b/src/writable_stream.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/writable-stream + * @see https://jsr.io/@nick/is/doc/writable-stream */ import { isObject } from "./object.ts"; diff --git a/src/writer.test.ts b/src/writer.test.ts index d5bc271..a9ab37d 100644 --- a/src/writer.test.ts +++ b/src/writer.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/writer - */ - import { assertEquals } from "@std/assert"; import { isWriter } from "./writer.ts"; diff --git a/src/writer.ts b/src/writer.ts index 5243ce2..58905e0 100644 --- a/src/writer.ts +++ b/src/writer.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/writer + * @see https://jsr.io/@nick/is/doc/writer */ /** diff --git a/src/writer_sync.test.ts b/src/writer_sync.test.ts index 4bd42de..8be2af5 100644 --- a/src/writer_sync.test.ts +++ b/src/writer_sync.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/writer-sync - */ - import { assertEquals } from "@std/assert"; import { isWriterSync } from "./writer_sync.ts"; diff --git a/src/writer_sync.ts b/src/writer_sync.ts index f20030c..9f6ece3 100644 --- a/src/writer_sync.ts +++ b/src/writer_sync.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/writer-sync + * @see https://jsr.io/@nick/is/doc/writer-sync */ /** From 4aa079aa78e8dc8be72f00639fcc05f17cc50068 Mon Sep 17 00:00:00 2001 From: Nicholas Berlette Date: Thu, 19 Jun 2025 01:53:34 +0000 Subject: [PATCH 04/24] docs(wiki): create github wiki submodule --- .gitmodules | 3 +++ wiki | 1 + 2 files changed, 4 insertions(+) create mode 100644 .gitmodules create mode 160000 wiki diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..bf4bfde --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "wiki"] + path = wiki + url = https://github.com/nberlette/is.wiki.git diff --git a/wiki b/wiki new file mode 160000 index 0000000..2d3d51a --- /dev/null +++ b/wiki @@ -0,0 +1 @@ +Subproject commit 2d3d51add15c2bb403f0113ff115cf493f69dda7 From 88f7820eb59b814f4865c7f76961c2217bc4fe06 Mon Sep 17 00:00:00 2001 From: Nicholas Berlette Date: Thu, 19 Jun 2025 17:17:32 +0000 Subject: [PATCH 05/24] chore: update wiki module --- wiki | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wiki b/wiki index 2d3d51a..8ee005f 160000 --- a/wiki +++ b/wiki @@ -1 +1 @@ -Subproject commit 2d3d51add15c2bb403f0113ff115cf493f69dda7 +Subproject commit 8ee005faf2bc6700e3b0941dd0da9631b352933d From 8ee36703a2b4090b3663bcb646b60ac38f65fa5c Mon Sep 17 00:00:00 2001 From: Nicholas Berlette Date: Sat, 21 Jun 2025 06:58:01 +0000 Subject: [PATCH 06/24] docs: add generated markdown docs --- docs/api.md | 57 + docs/arguments.md | 40 + docs/array-buffer-like.md | 57 + docs/array-buffer-view.md | 40 + docs/array-buffer.md | 43 + docs/array-iterator.md | 60 + docs/array-like-object.md | 91 + docs/array-like.md | 46 + docs/array.md | 51 + docs/async-disposable.md | 69 + docs/async-function.md | 35 + docs/async-generator-function.md | 53 + docs/async-generator.md | 47 + docs/async-iterable-iterator.md | 40 + docs/async-iterable-object.md | 86 + docs/async-iterable.md | 36 + docs/async-iterator.md | 38 + docs/bigint-object.md | 44 + docs/bigint.md | 37 + docs/bigint64-array.md | 35 + docs/biguint64-array.md | 35 + docs/boolean-object.md | 45 + docs/boolean.md | 33 + docs/both.md | 64 + docs/boxed-primitive.md | 69 + docs/buffer-source.md | 41 + docs/class.md | 96 + docs/closer.md | 59 + docs/constructor.md | 71 + docs/data-view.md | 36 + docs/date-string.md | 78 + docs/date.md | 39 + docs/defined.md | 52 + docs/disposable.md | 70 + docs/either.md | 51 + docs/empty-object.md | 129 + docs/empty.md | 182 + docs/enum.md | 217 + docs/error.md | 42 + docs/falsy.md | 86 + docs/float16-array.md | 35 + docs/float32-array.md | 35 + docs/float64-array.md | 35 + docs/function.md | 130 + docs/generator-function.md | 95 + docs/generator.md | 46 + docs/has-methods.md | 84 + docs/identifier.md | 148 + docs/index.md | 54 + docs/instance.md | 86 + docs/int16-array.md | 35 + docs/int32-array.md | 35 + docs/int8-array.md | 35 + docs/iterable-iterator.md | 37 + docs/iterable-object.md | 62 + docs/iterable.md | 40 + docs/iterator.md | 37 + docs/keyof.md | 29 + docs/map-iterator.md | 61 + docs/map-like.md | 249 + docs/map.md | 51 + docs/missing.md | 37 + docs/namespace.md | 13399 +++++++++++++++++++++++++++++ docs/non-array-object.md | 185 + docs/non-empty-array.md | 106 + docs/null.md | 37 + docs/number-object.md | 45 + docs/number.md | 7376 ++++++++++++++++ docs/object-like.md | 41 + docs/object.md | 41 + docs/plain-object.md | 42 + docs/present.md | 56 + docs/primitive.md | 67 + docs/printable.md | 72 + docs/promise-like.md | 37 + docs/promise.md | 40 + docs/property-key.md | 56 + docs/readable-stream.md | 40 + docs/reader-sync.md | 76 + docs/reader.md | 75 + docs/regexp.md | 37 + docs/registered-symbol.md | 122 + docs/semver.md | 73 + docs/set-iterator.md | 60 + docs/set-like.md | 765 ++ docs/set.md | 43 + docs/shared-array-buffer.md | 37 + docs/string-iterator.md | 62 + docs/string-object.md | 45 + docs/string.md | 37 + docs/symbol-object.md | 39 + docs/symbol.md | 36 + docs/tagged.md | 74 + docs/template-object.md | 85 + docs/template-strings-array.md | 87 + docs/truthy.md | 40 + docs/typed-array.md | 432 + docs/types.md | 4506 ++++++++++ docs/uint16-array.md | 35 + docs/uint32-array.md | 35 + docs/uint8-array.md | 35 + docs/uint8-clamped-array.md | 35 + docs/undefined.md | 52 + docs/unique-symbol.md | 50 + docs/url-search-params.md | 41 + docs/url-string.md | 56 + docs/url.md | 34 + docs/weak-key.md | 108 + docs/weak-map.md | 89 + docs/weak-ref.md | 73 + docs/weak-set.md | 85 + docs/well-known-symbol.md | 53 + docs/whitespace.md | 435 + docs/writable-stream.md | 40 + docs/writer-sync.md | 65 + docs/writer.md | 70 + 116 files changed, 33718 insertions(+) create mode 100644 docs/api.md create mode 100644 docs/arguments.md create mode 100644 docs/array-buffer-like.md create mode 100644 docs/array-buffer-view.md create mode 100644 docs/array-buffer.md create mode 100644 docs/array-iterator.md create mode 100644 docs/array-like-object.md create mode 100644 docs/array-like.md create mode 100644 docs/array.md create mode 100644 docs/async-disposable.md create mode 100644 docs/async-function.md create mode 100644 docs/async-generator-function.md create mode 100644 docs/async-generator.md create mode 100644 docs/async-iterable-iterator.md create mode 100644 docs/async-iterable-object.md create mode 100644 docs/async-iterable.md create mode 100644 docs/async-iterator.md create mode 100644 docs/bigint-object.md create mode 100644 docs/bigint.md create mode 100644 docs/bigint64-array.md create mode 100644 docs/biguint64-array.md create mode 100644 docs/boolean-object.md create mode 100644 docs/boolean.md create mode 100644 docs/both.md create mode 100644 docs/boxed-primitive.md create mode 100644 docs/buffer-source.md create mode 100644 docs/class.md create mode 100644 docs/closer.md create mode 100644 docs/constructor.md create mode 100644 docs/data-view.md create mode 100644 docs/date-string.md create mode 100644 docs/date.md create mode 100644 docs/defined.md create mode 100644 docs/disposable.md create mode 100644 docs/either.md create mode 100644 docs/empty-object.md create mode 100644 docs/empty.md create mode 100644 docs/enum.md create mode 100644 docs/error.md create mode 100644 docs/falsy.md create mode 100644 docs/float16-array.md create mode 100644 docs/float32-array.md create mode 100644 docs/float64-array.md create mode 100644 docs/function.md create mode 100644 docs/generator-function.md create mode 100644 docs/generator.md create mode 100644 docs/has-methods.md create mode 100644 docs/identifier.md create mode 100644 docs/index.md create mode 100644 docs/instance.md create mode 100644 docs/int16-array.md create mode 100644 docs/int32-array.md create mode 100644 docs/int8-array.md create mode 100644 docs/iterable-iterator.md create mode 100644 docs/iterable-object.md create mode 100644 docs/iterable.md create mode 100644 docs/iterator.md create mode 100644 docs/keyof.md create mode 100644 docs/map-iterator.md create mode 100644 docs/map-like.md create mode 100644 docs/map.md create mode 100644 docs/missing.md create mode 100644 docs/namespace.md create mode 100644 docs/non-array-object.md create mode 100644 docs/non-empty-array.md create mode 100644 docs/null.md create mode 100644 docs/number-object.md create mode 100644 docs/number.md create mode 100644 docs/object-like.md create mode 100644 docs/object.md create mode 100644 docs/plain-object.md create mode 100644 docs/present.md create mode 100644 docs/primitive.md create mode 100644 docs/printable.md create mode 100644 docs/promise-like.md create mode 100644 docs/promise.md create mode 100644 docs/property-key.md create mode 100644 docs/readable-stream.md create mode 100644 docs/reader-sync.md create mode 100644 docs/reader.md create mode 100644 docs/regexp.md create mode 100644 docs/registered-symbol.md create mode 100644 docs/semver.md create mode 100644 docs/set-iterator.md create mode 100644 docs/set-like.md create mode 100644 docs/set.md create mode 100644 docs/shared-array-buffer.md create mode 100644 docs/string-iterator.md create mode 100644 docs/string-object.md create mode 100644 docs/string.md create mode 100644 docs/symbol-object.md create mode 100644 docs/symbol.md create mode 100644 docs/tagged.md create mode 100644 docs/template-object.md create mode 100644 docs/template-strings-array.md create mode 100644 docs/truthy.md create mode 100644 docs/typed-array.md create mode 100644 docs/types.md create mode 100644 docs/uint16-array.md create mode 100644 docs/uint32-array.md create mode 100644 docs/uint8-array.md create mode 100644 docs/uint8-clamped-array.md create mode 100644 docs/undefined.md create mode 100644 docs/unique-symbol.md create mode 100644 docs/url-search-params.md create mode 100644 docs/url-string.md create mode 100644 docs/url.md create mode 100644 docs/weak-key.md create mode 100644 docs/weak-map.md create mode 100644 docs/weak-ref.md create mode 100644 docs/weak-set.md create mode 100644 docs/well-known-symbol.md create mode 100644 docs/whitespace.md create mode 100644 docs/writable-stream.md create mode 100644 docs/writer-sync.md create mode 100644 docs/writer.md diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..be4ab13 --- /dev/null +++ b/docs/api.md @@ -0,0 +1,57 @@ +--- +outline: deep +--- + +# API Examples + +This page demonstrates usage of some of the runtime APIs provided by VitePress. + +The main `useData()` API can be used to access site, theme, and page data for +the current page. It works in both `.md` and `.vue` files: + +```md + + +## Results + +### Theme Data + +
{{ theme }}
+ +### Page Data + +
{{ page }}
+ +### Page Frontmatter + +
{{ frontmatter }}
+``` + + + +## Results + +### Theme Data + +
{{ theme }}
+ +### Page Data + +
{{ page }}
+ +### Page Frontmatter + +
{{ frontmatter }}
+ +## More + +Check out the documentation for the +[full list of runtime APIs](https://vitepress.dev/reference/runtime-api#usedata). diff --git a/docs/arguments.md b/docs/arguments.md new file mode 100644 index 0000000..78a39eb --- /dev/null +++ b/docs/arguments.md @@ -0,0 +1,40 @@ +# @nick/is/arguments + +## `isArguments` + +#### Signature + +```ts ignore +function isArguments(it: unknown): it is IArguments; +``` + +Check if the given value is an instance of the native `Arguments` object, which +is a special type of Array-like object that corresponds to the binding arguments +of a particular JavaScript function. + +This check will return `false` for any other kind of array-like object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `Arguments` object, `false` otherwise. + +###### Category + +`Indexed Collections` + +#### Examples + +```ts +import { isArguments } from "jsr:@nick/is/arguments"; + +function foo() { + console.log(isArguments(arguments)); // true + console.log(isArguments([1, 2, 3])); // false +} +``` diff --git a/docs/array-buffer-like.md b/docs/array-buffer-like.md new file mode 100644 index 0000000..6ee396e --- /dev/null +++ b/docs/array-buffer-like.md @@ -0,0 +1,57 @@ +# @nick/is/array-buffer-like + +## `isArrayBufferLike` + +#### Signature + +```ts ignore +function isArrayBufferLike(it: unknown): it is ArrayBufferLike; +``` + +Checks if [`it`](#it "Jump to symbol: 'it'") is an `ArrayBuffer` or a +`SharedArrayBuffer`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `ArrayBuffer` or a `SharedArrayBuffer`, or `false` +otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isArrayBufferLike } from "jsr:@nick/is/any-array-buffer"; + +const buffer = new ArrayBuffer(8); +const shared = new SharedArrayBuffer(8); +const array = new Uint8Array(buffer); + +isArrayBufferLike(buffer); // true +isArrayBufferLike(shared); // true +isArrayBufferLike(array); // false +isArrayBufferLike(array.buffer); // true +``` + +## `ArrayBufferLike` + +#### Signature + +```ts ignore +export type ArrayBufferLike = ArrayBuffer | SharedArrayBuffer; +``` + +Represents an "ArrayBuffer-like" value, which is either an `ArrayBuffer` or +`SharedArrayBuffer` instance. + +###### Category + +`Binary Data Structures` diff --git a/docs/array-buffer-view.md b/docs/array-buffer-view.md new file mode 100644 index 0000000..299c3eb --- /dev/null +++ b/docs/array-buffer-view.md @@ -0,0 +1,40 @@ +# @nick/is/array-buffer-view + +## `isArrayBufferView` + +#### Signature + +```ts ignore +function isArrayBufferView(it: unknown): it is ArrayBufferView; +``` + +Checks if a value is an `ArrayBufferView`, which includes all typed arrays and +`DataView` objects, but not `ArrayBuffer` or `SharedArrayBuffer`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `ArrayBufferView`, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isArrayBufferView } from "jsr:@nick/is/array-buffer-view"; + +const buffer = new ArrayBuffer(8); +const view = new DataView(buffer); +const array = new Uint8Array(buffer); + +isArrayBufferView(buffer); // false +isArrayBufferView(view); // true +isArrayBufferView(array); // true +``` diff --git a/docs/array-buffer.md b/docs/array-buffer.md new file mode 100644 index 0000000..2e783dd --- /dev/null +++ b/docs/array-buffer.md @@ -0,0 +1,43 @@ +# @nick/is/array-buffer + +## `isArrayBuffer` + +#### Signature + +```ts ignore +function isArrayBuffer(it: unknown): it is ArrayBuffer; +``` + +Returns `true` if [`it`](#it "Jump to symbol: 'it'") is an `ArrayBuffer`. This +does not include instances of the `SharedArrayBuffer`, which has its own type +guard. To check for either type, use +[`isArrayBufferLike`](#isarraybufferlike "Jump to symbol: 'isArrayBufferLike'"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `ArrayBuffer`, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isArrayBuffer } from "jsr:@nick/is/array-buffer"; + +const buffer = new ArrayBuffer(8); +const shared = new SharedArrayBuffer(8); +const array = new Uint8Array(buffer); + +isArrayBuffer(buffer); // true +isArrayBuffer(shared); // false +isArrayBuffer(array); // false +isArrayBuffer(array.buffer); // true +``` diff --git a/docs/array-iterator.md b/docs/array-iterator.md new file mode 100644 index 0000000..6c67daf --- /dev/null +++ b/docs/array-iterator.md @@ -0,0 +1,60 @@ +# @nick/is/array-iterator + +## `isArrayIterator` + +#### Signature + +```ts ignore +function isArrayIterator(it: unknown): it is ArrayIterator; +``` + +Check if the given value is an array iterator, which is an iterable iterator +that yields key-value pairs from an Array. This is the type of value that is +returned by `Array.prototype.values` and `Array.prototype[Symbol.iterator]`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a array iterator, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isArrayIterator } from "jsr:@nick/is/array-iterator"; + +const array = ["foo", "bar", "foo"]; +const iter = array[Symbol.iterator](); +console.log(isArrayIterator(iterator)); // true +console.log(isArrayIterator(array)); // false +``` + +## `ArrayIterator` + +Represents a array iterator. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +##### Extends `IterableIterator` + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "Array Iterator"; +``` + +--- diff --git a/docs/array-like-object.md b/docs/array-like-object.md new file mode 100644 index 0000000..a206d0f --- /dev/null +++ b/docs/array-like-object.md @@ -0,0 +1,91 @@ +# @nick/is/array-like-object + +## `isArrayLikeObject` + +#### Signature + +```ts ignore +function isArrayLikeObject(it: unknown): it is ArrayLikeObject; +``` + +Checks if a given value is an `ArrayLike` object. This is a stricter form of the +[`isArrayLike`](#isarraylike "Jump to symbol: 'isArrayLike'") check that only +returns `true` if a value is an **_object_** that also meets all of the +`ArrayLike` conditions: + +- it is not a function +- it has an own property named `length` that is a finite unsigned integer: + - an integer between `0` and `Number.MAX_SAFE_INTEGER` + - it is non-negative, `NaN`, `Infinity`, nor `-Infinity` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an object that meets all of the `ArrayLike` conditions, +otherwise `false`. + +###### Category + +`Indexed Collections` + +###### See Also + +- [`isArrayLike`](#isarraylike "Jump to symbol: 'isArrayLike'") for a version + that allows for non-object values such as strings (but not functions). + +#### Examples + +```ts +import { isArrayLikeObject } from "jsr:@nick/is/array-like"; + +isArrayLikeObject([]); // true +isArrayLikeObject({ length: 0 }); // true +isArrayLikeObject({ length: 1, 0: "a" }); // true + +// strings are not considered ArrayLike objects +isArrayLikeObject("abc"); // false + +// length must be a finite unsigned integer +isArrayLikeObject({ length: Infinity }); // false + +// length must be non-negative +isArrayLikeObject({ length: -1 }); // false + +// length cannot be a non-number or NaN +isArrayLikeObject({ length: "a" }); // false +isArrayLikeObject({ length: NaN }); // false + +// functions are not considered ArrayLike objects, despite meeting the +// requirements for the 'length' property. this is because they are not +// indexed collections like an array or string. +isArrayLikeObject(() => {}); +``` + +## `ArrayLikeObject` + +#### Signature + +```ts ignore +export type ArrayLikeObject = ArrayLike & object; +``` + +Represents an object that has a `length` property that is a finite unsigned +integer, and where the object is not a function. This is the type that the +function +[`isArrayLikeObject`](#isarraylikeobject "Jump to symbol: 'isArrayLikeObject'") +narrows its inputs to. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +###### Category + +`Indexed Collections` diff --git a/docs/array-like.md b/docs/array-like.md new file mode 100644 index 0000000..3788776 --- /dev/null +++ b/docs/array-like.md @@ -0,0 +1,46 @@ +# @nick/is/array-like + +## `isArrayLike` + +#### Signature + +```ts ignore +function isArrayLike(it: unknown): it is ArrayLike; +``` + +Checks if a given value is `ArrayLike`, which is defined as +`any +non-function value with an own property named 'length' that is an integer, +and where 'length' >= '0' and <= 'Number.MAX_SAFE_INTEGER'`. + +This condition includes strings. If you'd like to check specifically for +`ArrayLike` _objects_, see +[`isArrayLikeObject`](#isarraylikeobject "Jump to symbol: 'isArrayLikeObject'") +instead. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if it is an ArrayLike value + +###### Category + +`Indexed Collections` + +#### Examples + +```ts +import { isArrayLike } from "jsr:@nick/is/array-like"; + +isArrayLike([]); // true +isArrayLike("abc"); // true +isArrayLike({ length: 0 }); // true +isArrayLike({ length: 1, 0: "a" }); // true +isArrayLike({ length: Infinity }); // false +isArrayLike({ length: -1 }); // false +``` diff --git a/docs/array.md b/docs/array.md new file mode 100644 index 0000000..1ff6ade --- /dev/null +++ b/docs/array.md @@ -0,0 +1,51 @@ +# @nick/is/array + +## `isArray` + +#### Signature + +```ts ignore +function isArray(a: unknown, test?: Predicate): a is T[]; +``` + +Checks if the given value is an array, optionally verifying that each of its +elements are of a specific type. + +##### Parameters + +| Name | Info | +| :--------- | :------------------------------------------------------ | +| **`it`** | The value to check. | +| **`test`** | The type guard to check the type of the array elements. | + +##### Returns + +`true` if it is an array, and the predicate (if provided) is satisfied by each +of its values. Otherwise, returns `false`. + +###### Category + +`Indexed Collections` + +#### Examples + +```ts +import { isArray, isNumber, isString } from "jsr:@nick/is"; +import { expectType } from "jsr:@nick/is/type/expect"; + +const arr: unknown[] = ["a", "b", "c"]; + +if (isArray(arr, isString)) { + console.log(arr, "is an array of strings"); + // ^? const arr: string[] + expectType(arr); +} else if (isArray(arr, isNumber)) { + console.log(arr, "is an array of numbers"); + // ^? const arr: number[] + expectType(arr); +} else { + console.log(arr, "is not an array of strings or numbers"); + // ^? const arr: unknown[] + expectType(arr); +} +``` diff --git a/docs/async-disposable.md b/docs/async-disposable.md new file mode 100644 index 0000000..527df88 --- /dev/null +++ b/docs/async-disposable.md @@ -0,0 +1,69 @@ +# @nick/is/async-disposable + +## `isAsyncDisposable` + +#### Signature + +```ts ignore +function isAsyncDisposable(it: unknown): it is AsyncDisposable; +``` + +Checks if a value is an object that implements the `AsyncDisposable` API. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an object that implements the `AsyncDisposable` API, or +`false` otherwise. + +###### Category + +`Explicit Resource Management` + +#### Examples + +```ts +import { isAsyncDisposable } from "@nick/is/async_disposable"; + +const disposable = { + [Symbol.dispose]() { + return; + }, +}; + +const asyncDisposable = { + async [Symbol.asyncDispose]() { + await Promise.resolve(); + }, +}; + +isAsyncDisposable(disposable); // false +isAsyncDisposable(asyncDisposable); // true +``` + +## `AsyncDisposable` + +Represents an object that can be asynchronously disposed of. + +###### Category + +`Explicit Resource Management` + +### Methods + +#### SymbolAsyncDispose + +```ts +SymbolAsyncDispose(): Promise< + void + >; +``` + +Asynchronously disposes of the resources held by this object. + +--- diff --git a/docs/async-function.md b/docs/async-function.md new file mode 100644 index 0000000..f2bc85b --- /dev/null +++ b/docs/async-function.md @@ -0,0 +1,35 @@ +# @nick/is/async-function + +## `isAsyncFunction` + +#### Signature + +```ts ignore +function isAsyncFunction(it: unknown): it is AsyncFunction; +``` + +## `AsyncFunction` + +##### Type Parameters + +- **`TReturn`** (default: `any`) + +--- + +### Call Signatures + +```ts +(...args: any[]): Promise; +``` + +--- + +### Properties + +#### `[Symbol.toStringTag]` + +```ts +readonly [Symbol.toStringTag]: "AsyncFunction"; +``` + +--- diff --git a/docs/async-generator-function.md b/docs/async-generator-function.md new file mode 100644 index 0000000..f3f9994 --- /dev/null +++ b/docs/async-generator-function.md @@ -0,0 +1,53 @@ +# @nick/is/async-generator-function + +## `isAsyncGeneratorFunction` + +#### Signature + +```ts ignore +function isAsyncGeneratorFunction(it: unknown): it is AsyncGeneratorFunction; +``` + +Checks if a given value is an async generator function, which is a function that +returns an async generator object when called, and was created with the +`async function*() { ... }` syntax. + +To check if a value is an async generator object, use `isAsyncGenerator`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an async generator function, `false` otherwise. + +###### Category + +`Generators` + +#### Examples + +```ts +import { + isAsyncGeneratorFunction, +} from "jsr:@nick/is/async-generator-function"; + +const genFnAsync = async function* () { + yield 1; +}; +isAsyncGeneratorFunction(genFnAsync); // true + +const genObjAsync = genFnAsync(); +isAsyncGeneratorFunction(genObjAsync); // false + +const genFn = function* () { + yield 1; +}; +isAsyncGeneratorFunction(genFn); // false + +const genObj = genFn(); +isAsyncGeneratorFunction(genObj); // false +``` diff --git a/docs/async-generator.md b/docs/async-generator.md new file mode 100644 index 0000000..62be1f0 --- /dev/null +++ b/docs/async-generator.md @@ -0,0 +1,47 @@ +# @nick/is/async-generator + +## `isAsyncGenerator` + +#### Signature + +```ts ignore +function isAsyncGenerator( + it: unknown, +): it is AsyncGenerator; +``` + +Check if the given value is an async generator, which is an asynchronous +iterable iterator (`AsyncIterableIterator`) that was created using the +`async function*() { ... }` syntax. + +This is the type of value **_returned_** when an async generator function +(`async function*() {}`) is called. To check for the function itself, use +`isAsyncGeneratorFunction` instead. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an AsyncGenerator, `false` otherwise. + +###### Category + +`Generators` + +#### Examples + +```ts +import { isAsyncGenerator } from "jsr:@nick/is/async-generator"; + +async function* genFn() { + yield await Promise.resolve(1); +} +const gen = genFn(); + +console.log(isAsyncGenerator(gen)); // true +console.log(isAsyncGenerator(genFn)); // false +``` diff --git a/docs/async-iterable-iterator.md b/docs/async-iterable-iterator.md new file mode 100644 index 0000000..7c2e082 --- /dev/null +++ b/docs/async-iterable-iterator.md @@ -0,0 +1,40 @@ +# @nick/is/async-iterable-iterator + +## `isAsyncIterableIterator` + +#### Signature + +```ts ignore +function isAsyncIterableIterator( + it: unknown, +): it is AsyncIterableIterator; +``` + +Checks if a value is an `AsyncIterableIterator`, which is an `AsyncIterator` +with a `Symbol.asyncIterator` method that returns a reference to itself. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `AsyncIterableIterator`, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import isAsyncIterableIterator from "jsr:@nick/is/async-iterable-iterator"; + +const iter = (async function* () { + yield 1; +})(); +console.log(isAsyncIterableIterator(iter)); // true +console.log(isAsyncIterableIterator(iter[Symbol.asyncIterator]())); // true +``` diff --git a/docs/async-iterable-object.md b/docs/async-iterable-object.md new file mode 100644 index 0000000..a4d18ed --- /dev/null +++ b/docs/async-iterable-object.md @@ -0,0 +1,86 @@ +# @nick/is/async-iterable-object + +## `isAsyncIterableObject` + +#### Signature + +```ts ignore +function isAsyncIterableObject(it: unknown): it is AsyncIterableObject; +``` + +Checks if a given value is an `AsyncIterable` object. + +Similar to its synchronous counterpart, `isIterableObject`, this function +requires the value to be a non-primitive (and non-null) object, and also +implement a `[Symbol.asyncIterator]` method as per the `AsyncIterable` API. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an iterable object, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isAsyncIterableObject } from "jsr:@nick/is/async-iterable-object"; + +// synchronous iterables will not pass +console.log(isAsyncIterableObject([1, 2])); // false +console.log(isAsyncIterableObject(new Map())); // false +console.log(isAsyncIterableObject(new Set())); // false + +// non-object iterables will not pass +console.log(isAsyncIterableObject("foo")); // false + +// only asynchronous iterable objects will pass +const iter = { + async *[Symbol.asyncIterator]() { + yield await Promise.resolve(1); + }, +}; +console.log(isAsyncIterableObject(iter)); // true +``` + +```ts +import { isAsyncIterableObject } from "jsr:@nick/is/async-iterable-object"; + +const kv = await Deno.openKv(); +console.log(isAsyncIterableObject(kv)); // false + +const iter = kv.list({ prefix: [] }); +console.log(isAsyncIterableObject(iter)); // true + +kv.close(); +``` + +## `AsyncIterableObject` + +#### Signature + +```ts ignore +export type AsyncIterableObject = AsyncIterable & object; +``` + +An object that implements the `AsyncIterable` interface. This is the type that +the +[isAsyncIterableObject](#isasynciterableobject "Jump to symbol: 'isAsyncIterableObject'") +function checks for and (narrows to). + +##### Type Parameters + +- **`T`** + +--- + +###### Category + +`Iterables` diff --git a/docs/async-iterable.md b/docs/async-iterable.md new file mode 100644 index 0000000..92ba576 --- /dev/null +++ b/docs/async-iterable.md @@ -0,0 +1,36 @@ +# @nick/is/async-iterable + +## `isAsyncIterable` + +#### Signature + +```ts ignore +function isAsyncIterable(it: unknown): it is AsyncIterable; +``` + +Checks if a given value is an object with a `Symbol.asyncIterator` method. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `AsyncIterable`, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isAsyncIterable } from "jsr:@nick/is/async-iterable"; + +const iter = (async function* () { + yield 1; +})(); +console.log(isAsyncIterable(iter)); // true +``` diff --git a/docs/async-iterator.md b/docs/async-iterator.md new file mode 100644 index 0000000..4cb16ae --- /dev/null +++ b/docs/async-iterator.md @@ -0,0 +1,38 @@ +# @nick/is/async-iterator + +## `isAsyncIterator` + +#### Signature + +```ts ignore +function isAsyncIterator(it: unknown): it is AsyncIterator; +``` + +Check if the given value is an async iterator, which is an object that has a +`"next"` method that returns a promise for an iterator result. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an async iterator, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isAsyncIterator } from "jsr:@nick/is/async-iterator"; + +const iter = (async function* () { + yield 1; +})(); +console.log(isAsyncIterator(iter)); // true +console.log(isAsyncIterator(iter[Symbol.asyncIterator]())); // true +``` diff --git a/docs/bigint-object.md b/docs/bigint-object.md new file mode 100644 index 0000000..35c9cc8 --- /dev/null +++ b/docs/bigint-object.md @@ -0,0 +1,44 @@ +# @nick/is/bigint-object + +## `isBigIntObject` + +#### Signature + +```ts ignore +function isBigIntObject(it: unknown): it is BigInt; +``` + +Checks if a value is a BigInt object, which is a boxed-primitive BigInt that was +created by wrapping a primitive BigInt (bigint) in the `Object()` wrapper +function. + +Boxed primitives are strongly discouraged in JavaScript, as they can lead to all +sorts of unexpected behavior and performance issues. As such, this function - +and the other boxed primitive functions like it - are provided for your +convenience, to help you easily ensure your code is not on the receiving end of +such behavior. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a boxed-primitive BigInt object; otherwise, `false`. + +###### Category + +`Boxed Primitives` + +#### Examples + +```ts +import { isBigIntObject } from "jsr:@nick/is/bigint-object"; + +isBigIntObject(Object(BigInt("2"))); // true + +isBigIntObject(BigInt("2")); // false +isBigIntObject(2n); // false +``` diff --git a/docs/bigint.md b/docs/bigint.md new file mode 100644 index 0000000..dd2ea62 --- /dev/null +++ b/docs/bigint.md @@ -0,0 +1,37 @@ +# @nick/is/bigint + +## `isBigInt` + +#### Signature + +```ts ignore +function isBigInt(it: unknown): it is bigint; +``` + +Checks if the given value is a primitive bigint value. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a primitive bigint, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isBigInt } from "jsr:@nick/is/bigint"; + +const x: unknown = 123n; +if (isBigInt(x)) { + console.log(x + 1n); + // ^? const x: bigint +} +``` diff --git a/docs/bigint64-array.md b/docs/bigint64-array.md new file mode 100644 index 0000000..12ac6f3 --- /dev/null +++ b/docs/bigint64-array.md @@ -0,0 +1,35 @@ +# @nick/is/bigint64-array + +## `isBigInt64Array` + +#### Signature + +```ts ignore +function isBigInt64Array(it: unknown): it is BigInt64Array; +``` + +Check if the given value is a `BigInt64Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `BigInt64Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isBigInt64Array } from "jsr:@nick/is/bigint64array"; + +const arr = new BigInt64Array(8); +isBigInt64Array(arr); // true +isBigInt64Array(arr.buffer); // false +``` diff --git a/docs/biguint64-array.md b/docs/biguint64-array.md new file mode 100644 index 0000000..0d4e66d --- /dev/null +++ b/docs/biguint64-array.md @@ -0,0 +1,35 @@ +# @nick/is/biguint64-array + +## `isBigUint64Array` + +#### Signature + +```ts ignore +function isBigUint64Array(it: unknown): it is BigUint64Array; +``` + +Check if the given value is a `BigUint64Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `BigUint64Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isBigUint64Array } from "jsr:@nick/is/biguint64array"; + +const arr = new BigUint64Array(8); +isBigUint64Array(arr); // true +isBigUint64Array(arr.buffer); // false +``` diff --git a/docs/boolean-object.md b/docs/boolean-object.md new file mode 100644 index 0000000..613a1bc --- /dev/null +++ b/docs/boolean-object.md @@ -0,0 +1,45 @@ +# @nick/is/boolean-object + +## `isBooleanObject` + +#### Signature + +```ts ignore +function isBooleanObject(it: unknown): it is Boolean; +``` + +Checks if a value is a Boolean object, which is a boxed-primitive boolean that +was created either with the `new Boolean()` syntax, or by wrapping a primitive +boolean in the `Object()` wrapper function. + +Boxed primitives are strongly discouraged in JavaScript, as they can lead to all +sorts of unexpected behavior and performance issues. As such, this function - +and the other boxed primitive functions like it - are provided for your +convenience, to help you easily ensure your code is not on the receiving end of +such behavior. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a boxed-primitive boolean object; otherwise, `false`. + +###### Category + +`Boxed Primitives` + +#### Examples + +```ts +import { isBooleanObject } from "jsr:@nick/is/boolean-object"; + +isBooleanObject(Object(true)); // true +isBooleanObject(new Boolean(true)); // true + +isBooleanObject(Boolean(true)); // false +isBooleanObject(true); // false +``` diff --git a/docs/boolean.md b/docs/boolean.md new file mode 100644 index 0000000..dc4ba92 --- /dev/null +++ b/docs/boolean.md @@ -0,0 +1,33 @@ +# @nick/is/boolean + +## `isBoolean` + +#### Signature + +```ts ignore +function isBoolean(it: unknown): it is boolean; +``` + +Checks if the given value is a boolean. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a boolean, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isBoolean } from "jsr:@nick/is/boolean"; +isBoolean("true"); // false +isBoolean(true); // true +``` diff --git a/docs/both.md b/docs/both.md new file mode 100644 index 0000000..e1a32c3 --- /dev/null +++ b/docs/both.md @@ -0,0 +1,64 @@ +# @nick/is/both + +## `isBoth` + +#### Signature + +```ts ignore +function isBoth( + left: (it: any, ...args: any[]) => it is L, + right: (it: any, ...args: any[]) => it is R, +): (it: unknown) => it is L & R; +``` + +Combine two different predicates into one, such that the resulting function +returns `true` if a given input satisfies **both** of the two predicates. + +This creates a logical AND between the two predicates, narrowing types to an +intersection of the two original predicates' return types. This helps you +compose custom reusable type guards with ease, reducing boilerplate and +repetition. + +**Note**: just like in the rest of TypeScript code, if you attempt to use an +incompatible pair of predicates in this function, the resulting type it will +narrow to will probably be `never`. For this reason, don't use this function to +combine mutually exclusive predicates like `isString` and `isNumber`. + +##### Parameters + +| Name | Info | +| :---------- | :----------------------------- | +| **`left`** | The first predicate to check. | +| **`right`** | The second predicate to check. | + +##### Returns + +A new predicate that returns `true` if both +[left](#left "Jump to symbol: 'left'") and +[right](#right "Jump to symbol: 'right'") are satisfies by a given input. + +###### Category + +`Composition` + +#### Examples + +```ts +import { is, isBoth } from "@nick/is"; + +// creating a custom type guard by hand +const isEmpty = ( + it: T, +): it is T & { readonly length: 0 } => ( + "length" in Object(it) && Object(it).length === 0 +); + +// composing a custom type guard with `isBoth` +const isEmptyString = isBoth(is.string, isEmpty); +// ^? const isEmptyString: (it: unknown) => it is string & { readonly length: 0 } + +// using the custom type guard +isEmptyString(""); // true +isEmptyString("foo"); // false +isEmptyString([]); // false +``` diff --git a/docs/boxed-primitive.md b/docs/boxed-primitive.md new file mode 100644 index 0000000..e064e57 --- /dev/null +++ b/docs/boxed-primitive.md @@ -0,0 +1,69 @@ +# @nick/is/boxed-primitive + +## `isBoxedPrimitive` + +Checks if a value is a boxed-primitive object, which is an object that was +created by wrapping a primitive value in the `Object()` wrapper function, or by +using the `new` operator with the `String`, `Number`, or `Boolean` constructors +(`Symbol` and `BigInt` do not support the `new` operator). + +Boxed primitives are strongly discouraged in JavaScript, as they can lead to all +sorts of unexpected behavior and performance issues. As such, this function - +and the other boxed primitive functions like it - are provided for your +convenience, to help you easily ensure your code is not on the receiving end of +such behavior. + +#### Signature + +```ts ignore +function isBoxedPrimitive( + it: T | {} | null | undefined, +): it is T; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a boxed-primitive object; otherwise, `false`. + +###### Category + +`Boxed Primitives` + +#### Examples + +```ts +import { isBoxedPrimitive } from "jsr:@nick/is/boxed-primitive"; + +isBoxedPrimitive(new String("abc")); // true +isBoxedPrimitive(new Number(42)); // true +isBoxedPrimitive(new Boolean(true)); // true + +isBoxedPrimitive("abc"); // false +isBoxedPrimitive(42); // false +isBoxedPrimitive(true); // false +``` + +--- + +## `BoxedPrimitive` + +Type representing a boxed-primitive object, which is an object created by +wrapping a primitive value in the `Object()` wrapper function, or by using the +`new` operator with the `String`, `Number`, or `Boolean` constructors (`Symbol` +and `BigInt` do not support the `new` operator). + +#### Signature + +```ts ignore +export type BoxedPrimitive = String | Number | Boolean | Symbol | BigInt; +``` + +###### Category + +`Boxed Primitives` diff --git a/docs/buffer-source.md b/docs/buffer-source.md new file mode 100644 index 0000000..e9d6291 --- /dev/null +++ b/docs/buffer-source.md @@ -0,0 +1,41 @@ +# @nick/is/buffer-source + +## `isBufferSource` + +#### Signature + +```ts ignore +function isBufferSource(it: unknown): it is BufferSource; +``` + +Returns `true` if [`it`](#it "Jump to symbol: 'it'") is an `ArrayBuffer`, +`SharedArrayBuffer`, or an `ArrayBufferView`, which includes `TypedArray`s and +`DataView`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a BufferSource object, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isBufferSource } from "jsr:@nick/is/buffer-source"; + +const buffer = new ArrayBuffer(8); +const view = new DataView(buffer); +const array = new Uint8Array(buffer); + +isBufferSource(buffer); // true +isBufferSource(view); // true +isBufferSource(array); // true +``` diff --git a/docs/class.md b/docs/class.md new file mode 100644 index 0000000..d479669 --- /dev/null +++ b/docs/class.md @@ -0,0 +1,96 @@ +# @nick/is/class + +## `isClass` + +#### Signature + +```ts ignore +function isClass< + T, + A extends readonly unknown[] = readonly any[], + P extends object | null = Is, +>(it: unknown): it is Class; +``` + +Checks if a given value is a constructor function, also known as a class. + +This includes all **pure** functions - no generators, arrow functions, or +getters/setters - that also have an own `prototype` propertty which is a +non-null object. The prototype must have an own `constructor` property that +points back to the class constructor function itself. Lastly, the function's +source code is inspected for the `class` keyword, to ensure that it is a class +and not just a regular function. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a class, `false` otherwise. + +###### Category + +`Objects` + +#### Examples + +```ts +import { isClass } from "jsr:@nick/is/class"; + +class Foo {} +console.log(isClass(Foo)); // true + +const Bar = function () { + this.foo = "bar"; + return this; +}; +console.log(isClass(Bar)); // false + +const Baz = () => {}; +console.log(isClass(Baz)); // false +``` + +## `Class` + +###### Category + +`Types` + +#### Examples + +```ts +import { isClass } from "jsr:@nick/is/class"; + +class Foo {} +console.log(isClass(Foo)); // true + +const Bar = function () { + this.foo = "bar"; + return this; +}; +console.log(isClass(Bar)); // false + +const Baz = () => {}; +console.log(isClass(Baz)); // false +``` + +##### Type Parameters + +- **`T`** (default: `any`) +- **`A`** extends `readonly unknown[]` (default: `readonly any[]`) +- **`P`** extends `object | null` (default: `Is`) + +--- + +### Properties + +#### prototype + +```ts +readonly prototype: P; +``` + +--- diff --git a/docs/closer.md b/docs/closer.md new file mode 100644 index 0000000..2d118ca --- /dev/null +++ b/docs/closer.md @@ -0,0 +1,59 @@ +# @nick/is/closer + +## `isCloser` + +#### Signature + +```ts ignore +function isCloser(it: unknown): it is Closer; +``` + +Checks if a given value implments the `Deno.Closer` interface, which means it +has a `close` method that can be called to release associated resources. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value implements `Deno.Closer`, `false` otherwise. + +###### Category + +`I/O` + +#### Examples + +```ts +import { isCloser } from "jsr:@nick/is/closer"; + +const file = await Deno.open("file.txt"); +isCloser(file); // true + +const socket = new WebSocket("ws://example.com"); +isCloser(socket); // true +``` + +## `Closer` + +An abstract interface which when implemented provides an interface to close +files/resources that were previously opened. + +###### Category + +`I/O` + +### Methods + +#### close + +```ts +close(): void; +``` + +Closes the resource, "freeing" the backing file/resource. + +--- diff --git a/docs/constructor.md b/docs/constructor.md new file mode 100644 index 0000000..7f317bd --- /dev/null +++ b/docs/constructor.md @@ -0,0 +1,71 @@ +# @nick/is/constructor + +## `isConstructor` + +#### Signature + +```ts ignore +function isConstructor(it: unknown): it is Constructor; +``` + +Checks whether a given value is a constructor function. + +In this context, a constructor is defined as a function with a `prototype` own +property that contains an object with an own `constructor` property that points +back to the constructor function itself. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a constructor function; otherwise, `false`. + +###### Category + +`Guards` + +#### Examples + +```ts +import { isConstructor } from "jsr:@nick/is/constructor"; + +class Foo {} +console.log(isConstructor(Foo)); // true +console.log(isConstructor(Foo.prototype.constructor)); // true +console.log(isConstructor(class {})); // true +console.log(isConstructor(function () {})); // true + +console.log(isConstructor({})); // false +console.log(isConstructor(null)); // false +console.log(isConstructor(Foo.prototype)); // false +console.log(isConstructor(() => new Foo())); // false +``` + +## `Constructor` + +Represents a constructor function that creates instances of type `T`. + +###### Category + +`Types` + +##### Type Parameters + +- **`T`** (default: `unknown`) +- **`A`** extends `readonly unknown[]` (default: `readonly unknown[]`) + +--- + +### Properties + +#### prototype + +```ts +readonly prototype: Prototype; +``` + +--- diff --git a/docs/data-view.md b/docs/data-view.md new file mode 100644 index 0000000..71dcd12 --- /dev/null +++ b/docs/data-view.md @@ -0,0 +1,36 @@ +# @nick/is/data-view + +## `isDataView` + +#### Signature + +```ts ignore +function isDataView(it: unknown): it is DataView; +``` + +Checks if a given value is a `DataView`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `DataView`, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isDataView } from "jsr:@nick/is/data-view"; + +const buffer = new ArrayBuffer(8); +const view = new DataView(buffer); +console.log(isDataView(view)); // true +console.log(isDataView(buffer)); // false +``` diff --git a/docs/date-string.md b/docs/date-string.md new file mode 100644 index 0000000..9284494 --- /dev/null +++ b/docs/date-string.md @@ -0,0 +1,78 @@ +# @nick/is/date-string + +## `isDateString` + +#### Signature + +```ts ignore +function isDateString(it: unknown): it is DateString; +``` + +Checks if a given value is a valid date string. + +The term "date string" refers to any string that can be parsed by the native +`Date` constructor as-is, without the help of any external libraries or any +preparatory formatting. One of the most common formats is ISO 8601, which is +what the native `Date` constructor itself uses in the `toDateString()` and +`toISOString()` methods. + +Note: This function does not check if the date string is in a specific format +like ISO 8601. It only checks if the string can be parsed into a valid Date +instance. + +Values that fail to pass this check would be expected to result in `NaN` when +passed to the `Date` constructor and coerced to a primitive number (e.g. +`+new Date("2023-13-01")`). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a valid date string; otherwise, `false`. + +###### Category + +`Guards` + +#### Examples + +```ts +import { isDateString } from "@nick/is/date_string"; + +console.assert(isDateString("4/20/2024"), "it works!"); +console.assert(isDateString("2024-04-20"), "it works!"); +console.assert(isDateString("02.32.2025"), "wtf lol"); +``` + +## `DateString` + +#### Signature + +```ts ignore +export type DateString = string & IsDateString; +``` + +Represents a valid date string that can be parsed by the native `Date` +constructor without any additional formatting or help from external tools. + +This is a branded nominal type that can be used to strictly distinguish between +regular strings and those that have been validated as date strings through a +runtime check like +[`isDateString`](#isdatestring "Jump to symbol: 'isDateString'"). + +Combined with the aforementioned type guard, this type allows you to enforce the +validity of date strings both at runtime and compile time. If your users are not +exposed to this type alias, the only way a value of this type can be created is +by satisfying the `isDateString` function check. + +###### Category + +`Types` + +###### Tags + +`date-string` `nominal` diff --git a/docs/date.md b/docs/date.md new file mode 100644 index 0000000..160eb3c --- /dev/null +++ b/docs/date.md @@ -0,0 +1,39 @@ +# @nick/is/date + +## `isDate` + +#### Signature + +```ts ignore +function isDate(it: unknown): it is Date; +``` + +Checks if a given value is a `Date` instance. This is a more reliable check than +`it instanceof Date` because it also works across different realms. + +This only returns `true` for values that are valid `Date` instances, meaning +`Object.create(Date.prototype)` and similar constructs will return `false`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Date` instance, `false` otherwise. + +###### Category + +`Standard` + +#### Examples + +```ts +import { isDate } from "jsr:@nick/is/date"; + +isDate(new Date()); // true +isDate(new Date(0)); // true +isDate(new Date("2021-01-01")); // true +``` diff --git a/docs/defined.md b/docs/defined.md new file mode 100644 index 0000000..39c025b --- /dev/null +++ b/docs/defined.md @@ -0,0 +1,52 @@ +# @nick/is/defined + +## `isDefined` + +#### Signature + +```ts ignore +function isDefined(it: T | undefined): it is T; +``` + +Checks if a value is not `undefined`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is not `undefined`, or `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isDefined } from "jsr:@nick/is/defined"; + +isDefined(null); // true +isDefined(undefined); // false +isDefined(0); // true +isDefined(void 0); // false +isDefined(""); // true +``` + +```ts +import { isDefined } from "jsr:@nick/is/defined"; + +let value: number | undefined; +if (isDefined(value)) { + value += 1; + // ^? let value: number +} else { + value; + // ^? let value: undefined + value = 0; + // ^? let value: number | undefined +} +``` diff --git a/docs/disposable.md b/docs/disposable.md new file mode 100644 index 0000000..7ec843e --- /dev/null +++ b/docs/disposable.md @@ -0,0 +1,70 @@ +# @nick/is/disposable + +## `isDisposable` + +#### Signature + +```ts ignore +function isDisposable(it: unknown): it is Disposable; +``` + +Checks if a value is an object that implements the `Disposable` API. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an object that implements the `Disposable` API, or +`false` otherwise. + +###### Category + +`Explicit Resource Management` + +#### Examples + +```ts +import { isDisposable } from "@nick/is/disposable"; + +const disposable = { + [Symbol.dispose]() { + return; + }, +}; + +const asyncDisposable = { + async [Symbol.asyncDispose]() { + await Promise.resolve(); + }, +}; + +isDisposable(disposable); // true +isDisposable(asyncDisposable); // false +``` + +## `Disposable` + +An object that can have its resources explicitly released when it is no longer +needed. Objects that implement this interface can be used with the `using` and +`await using` statements, which automatically dispose of their resources when +they are no longer needed. + +###### Category + +`Explicit Resource Management` + +### Methods + +#### SymbolDispose + +```ts +SymbolDispose(): void; +``` + +Releases the resources held by this object. + +--- diff --git a/docs/either.md b/docs/either.md new file mode 100644 index 0000000..3b644da --- /dev/null +++ b/docs/either.md @@ -0,0 +1,51 @@ +# @nick/is/either + +## `isEither` + +#### Signature + +```ts ignore +function isEither( + left: (it: any, ...args: any[]) => it is L, + right: (it: any, ...args: any[]) => it is R, +): (it: unknown) => it is L | R; +``` + +Combine two different predicates into one, such that the resulting function +returns `true` if a given input satisfies **either** of the two predicates. + +This creates a logical OR between the two predicates, narrowing types to a union +of the two original predicates' return types. This helps you compose custom +reusable type guards with ease, reducing boilerplate and repetition. + +##### Parameters + +| Name | Info | +| :---------- | :----------------------------- | +| **`left`** | The first predicate to check. | +| **`right`** | The second predicate to check. | + +##### Returns + +A new predicate that returns `true` if either +[left](#left "Jump to symbol: 'left'") or +[right](#right "Jump to symbol: 'right'") are satisfies by a given input. + +###### Category + +`Composition` + +#### Examples + +```ts +import { isEither, isString, isSymbol } from "@nick/is"; + +// creating a custom type guard that checks for strings or symbols +const isStringOrSymbol = isEither(isString, isSymbol); +// ^? const isStringOrSymbol: (it: unknown) => it is string | symbol + +// using the custom type guard +isStringOrSymbol("foo"); // true +isStringOrSymbol(Symbol.iterator); // true +isStringOrSymbol(123); // false +``` diff --git a/docs/empty-object.md b/docs/empty-object.md new file mode 100644 index 0000000..e572315 --- /dev/null +++ b/docs/empty-object.md @@ -0,0 +1,129 @@ +# @nick/is/empty-object + +## `isEmptyObject` + +#### Signature + +```ts ignore +function isEmptyObject(it: unknown): it is EmptyObject; +``` + +Check if a value is an empty object. + +##### Parameters + +| Name | Info | +| :---------- | :------------------ | +| **`value`** | The value to check. | + +##### Returns + +`true` if the value is an empty object, or `false` otherwise. + +###### Category + +`Objects` + +#### Examples + +```ts +import { isEmptyObject } from "jsr:@nick/is/empty-object"; + +console.log(isEmptyObject({})); // true +console.log(isEmptyObject(new Object())); // true + +console.log(isEmptyObject({ a: 1 })); // false +console.log(isEmptyObject({ a: 1, b: 2 })); // false +console.log(isEmptyObject([])); // false +console.log(isEmptyObject(null)); // false +console.log(isEmptyObject(undefined)); // false +console.log(isEmptyObject(1)); // false +``` + +## `EmptyObject` + +#### Signature + +```ts ignore +export type EmptyObject = { + [_ in undefined]?: never; +}; +``` + +Represents an empty object with no own properties. + +###### Category + +`Objects` + +#### Examples + +```ts +import type { EmptyObject } from "jsr:@nick/is/empty-object"; + +const foo: EmptyObject = {}; // OK +const bar: EmptyObject = []; // ts(6133): Type 'never[]' has no properties in common with type 'EmptyObject'. +``` + +## `IsEmptyObject` + +#### Signature + +```ts ignore +export type IsEmptyObject = [T] extends [never] + ? False + : boolean extends (T extends never ? true : false) ? False + : [T] extends [EmptyObject] ? True + : T extends object + ? object extends T ? False + : [Exclude] extends [never] ? True + : False + : False; +``` + +Type-level predicate that checks if a value is an empty object. This is the type +equivalent of the +[`isEmptyObject`](#isemptyobject "Jump to symbol: 'isEmptyObject'") function. + +It also supports custom true/false types, allowing you to construct your own +type guards with the desired return type, or create conditional types that +depend on the emptiness of an object. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Categories + +`Objects` `Type Guards` + +###### See Also + +- [`EmptyObject`](#emptyobject "Jump to symbol: 'EmptyObject'") for the type + that represents an empty object. +- [`isEmptyObject`](#isemptyobject "Jump to symbol: 'isEmptyObject'") for the + runtime equivalent of this type. + +#### Examples + +```ts +import type { IsEmptyObject } from "jsr:@nick/is/empty-object"; + +type A = IsEmptyObject<{}>; // true +type B = IsEmptyObject<{ a: 1 }>; // false +type C = IsEmptyObject<[]>; // false +``` + +```ts +import type { IsEmptyObject } from "jsr:@nick/is/empty-object"; + +type PickEmptyObjectProperties = { + [K in keyof T as IsEmptyObject]: T[K]; + // shorthand conditionals true ^ ^ false + // equivalent to: IsEmptyObject extends true ? K : never +}; +``` diff --git a/docs/empty.md b/docs/empty.md new file mode 100644 index 0000000..a5e8cd3 --- /dev/null +++ b/docs/empty.md @@ -0,0 +1,182 @@ +# @nick/is/empty + +## `isEmpty` + +#### Signature + +```ts ignore +function isEmpty(it: string): it is ""; +``` + +Checks if a given value is an empty string. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an empty string, `false` otherwise. + +###### Category + +`Chain` + +#### Examples + +```ts +import { isEmpty } from "@nick/is/empty"; + +isEmpty(""); // true +isEmpty("a"); // false +``` + +## `isEmpty` + +#### Signature + +```ts ignore +function isEmpty(it: readonly unknown[]): it is readonly []; +``` + +Checks if a given value is an empty Array object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an empty Array object, `false` otherwise. + +###### Category + +`Chain` + +#### Examples + +```ts +import { isEmpty } from "@nick/is/empty"; + +isEmpty([]); // true +isEmpty([1]); // false +``` + +## `isEmpty` + +#### Signature + +```ts ignore +function isEmpty>(it: U): it is U & { + readonly length: 0; +}; +``` + +Checks if a given value is an empty ArrayLike object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an empty ArrayLike object, `false` otherwise. + +###### Category + +`Chain` + +#### Examples + +```ts +import { isEmpty } from "@nick/is/empty"; + +isEmpty([]); // true +isEmpty([1]); // false +``` + +## `isEmpty` + +#### Signature + +```ts ignore +function isEmpty(it: unknown): it is { + [K in undefined]: never; +}; +``` + +Checks if a given value is an empty object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an empty object, `false` otherwise. + +###### Category + +`Chain` + +#### Examples + +```ts +import { isEmpty } from "@nick/is/empty"; + +isEmpty({}); // true +isEmpty({ a: 1 }); // false +``` + +## `isEmpty` + +#### Signature + +```ts ignore +function isEmpty(it: unknown): it is + | "" + | { + length: 0; + } + | { + [K in undefined]: never; + }; +``` + +Checks if a given value is an empty object, array, or string. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an empty object, array, or string, `false` otherwise. + +###### Category + +`Chain` + +#### Examples + +```ts +import { isEmpty } from "@nick/is/empty"; + +isEmpty({}); // true +isEmpty([]); // true +isEmpty(""); // true + +isEmpty({ a: 1 }); // false +isEmpty([1]); // false +isEmpty("a"); // false +``` diff --git a/docs/enum.md b/docs/enum.md new file mode 100644 index 0000000..0777937 --- /dev/null +++ b/docs/enum.md @@ -0,0 +1,217 @@ +# @nick/is/enum + +## `isEnum` + +#### Signature + +```ts ignore +function isEnum(it: T | unknowns): it is Enum; +``` + +Check if the given value appears to be a TypeScript `enum` object, which is a +plain object with either all string keys that point to numeric or string values, +or string/numeric keys that point to string/numeric values, which are inversely +mapped to each other (e.g. `A.B === 1 && A[1] === "B"`). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value appears to be a TypeScript `enum` object, `false` otherwise. + +###### Category + +`Objects` + +#### Examples + +```ts +import { isEnum } from "@nick/is/enum"; + +enum Foo { + Bar, // 0 + Baz, // 1 + Qux, // 2 + // implicit reverse mapping: + // 0: "Bar", 1: "Baz", 2: "Qux", +} + +isEnum(Foo); // true + +const obj = { Bar: 0, Baz: 1, Qux: 2 }; +isEnum(obj); // false +``` + +## `isEnum` + +#### Signature + +```ts ignore +function isEnum(it: unknown): it is Enum; +``` + +## `isEnum` + +#### Signature + +```ts ignore +function isEnum(it: unknown): it is Enum; +``` + +## `Enum` + +#### Signature + +```ts ignore +export type Enum = EnumLike & T; +``` + +Represents a TypeScript `enum` object, which is defined as a plain object that +satisfies one of the following conditions: + +- String or numeric keys mapped to string or numeric values. +- Values can be constant or computed. + +> Declared keys may only be literal static strings. Numeric keys are not allowed +> in the declaration of an enum. The only legal way to create an enum with +> numeric keys like `"0"` is for the compiler to generate them. + +String-to-string enums **may not** have reverse mappings. It is only supported +for constant numeric values (whether explicitly specified via initializers, or +implicitly assigned by the TS compiler). + +> When defined with the `enum` keyword and constant numeric values (or no +> explicit values specified at all, which defaults to `0` for the first key and +> increments by `1` for each subsequent key), the TypeScript compiler +> auto-generates an implicit reverse-mapping from the values back to their +> respective keys. + +##### Type Parameters + +- **`T`** extends `EnumLike` (default: `EnumLike`) + +--- + +#### Examples + +Constant enum definition + +```ts +enum Abc { + B = 0, + C = 1, +} +``` + +Mixed-value enum definition (no reverse mapping) + +```ts +// Mixing string and numeric values in an enum definition will +// prevent the compiler from generating reverse mappings (since +// it only generates such mappings for constant numeric values). +enum Abc { + B = 0, + C = "c", +} +``` + +Constant enum definition (implicit value assignment) + +```ts +// auto-generates a reverse mapping from 0 => B and 1 => C +enum Abc { + B, // = 0 + C, // = 1 + // "0" = "B", + // "1" = "C", +} +``` + +Computed enum definition + +```ts +enum C { + D = "e" + "f", // "ef" +} +``` + +## `EnumLike` + +Represents an "enum-like" object, which is a plain object composed of either all +string keys and string values, or a two-way mapping of string keys to numeric +values (and vice versa). + +This is a supertype of the type of object created by TypeScript's builtin `enum` +keyword. Its primary consumer is the +[`isEnum`](#isenum "Jump to symbol: 'isEnum'") function. + +###### Category + +`Types` + +###### Tags + +`enum` `objects` + +#### Examples + +```ts +// when we create an enum with constant numeric values, the TypeScript +// compiler auto-generates an implicit reverse-mapping from the values +// back to their respective keys, providing us with the capability to +// access the keys by their values. +enum Priority { + Low = 0x0, + Medium = 0x1, + High = 0x2, + Insane = 0xFF, +} + +// the actual object generated by the enum syntax above looks like this: +const Priority = { + Low: 0, + Medium: 1, + High: 2, + Insane: 255, + "0": "Low", + "1": "Medium", + "2": "High", + "255": "Insane", +} satisfies EnumLike; + +// this provides us with the ability to access a key even when we only have +// its value, a language feature that is popular in other OOP languages such +// as C#, Java, and C++: + +console.log(Priority.High); // 2 +console.log(Priority[2]); // "High" +console.assert(Priority.High === Priority[Priority[2]]); +console.assert(Priority[2] === Priority[Priority.High]); +``` + +##### Type Parameters + +- **`K`** extends `string | number` (default: `string | number`) +- **`V`** extends `string | number` (default: `string | number`) + +--- + +### Index Signatures + +#### EnumLike + +```ts +readonly [key: string]: K | V | undefined +``` + +#### EnumLike + +```ts +readonly [index: number]: K +``` + +--- diff --git a/docs/error.md b/docs/error.md new file mode 100644 index 0000000..9d2a659 --- /dev/null +++ b/docs/error.md @@ -0,0 +1,42 @@ +# @nick/is/error + +## `isError` + +#### Signature + +```ts ignore +function isError(it: unknown): it is Error; +``` + +Check if the given value is an instance of the native Error class, or of a +subclass that inherits from it, like `TypeError` or `RangeError`. + +This is more reliable than `instanceof Error`, because it also works across +different realms (e.g. iframes / web workers / browser tabs). It's also more +strict than `instanceof` because it **does not** recognize objects that were +created with `Object.create(Error.prototype)` or `Object.setPrototypeOf` as +being a subclass of `Error`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an error, `false` otherwise. + +###### Category + +`Standard` + +#### Examples + +```ts +import { isError } from "jsr:@nick/is/error"; + +const err = new Error("Something went wrong"); +console.log(isError(err)); // true +console.log(isError(err.message)); // false +``` diff --git a/docs/falsy.md b/docs/falsy.md new file mode 100644 index 0000000..f9dc2af --- /dev/null +++ b/docs/falsy.md @@ -0,0 +1,86 @@ +# @nick/is/falsy + +## `isFalsy` + +#### Signature + +```ts ignore +function isFalsy(it: unknown): it is Falsy; +``` + +Check if the given value is falsy. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is falsy, `false` otherwise. + +#### Examples + +```ts +import { isFalsy } from "@nick/is/falsy"; + +isFalsy(null); // true +isFalsy(undefined); // true +isFalsy(0); // true +isFalsy(""); // true +isFalsy(false); // true +isFalsy([]); // false +``` + +## `Falsy` + +#### Signature + +```ts ignore +export type Falsy = null | undefined | void | false | 0 | 0n | "" | NaN; +``` + +A type that represents all falsy values. + +###### Category + +`Primitives` + +## `IsFalsy` + +#### Signature + +```ts ignore +export type IsFalsy = [T] extends [never] ? False + : [Exclude] extends [never] ? True + : False; +``` + +If type [`T`](#t "Jump to symbol: 'T'") is falsy, returns +[`True`](#true "Jump to symbol: 'True'") (default: true), otherwise returns +[`False`](#false "Jump to symbol: 'False'") (default: false). + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +#### Signature + +```ts ignore +type X = IsFalsy; // true +type Y = IsFalsy<"">; // true +type Z = IsFalsy<0>; // true +type A = IsFalsy; // true +type B = IsFalsy<[]>; // false +``` diff --git a/docs/float16-array.md b/docs/float16-array.md new file mode 100644 index 0000000..8c39e7a --- /dev/null +++ b/docs/float16-array.md @@ -0,0 +1,35 @@ +# @nick/is/float16-array + +## `isFloat16Array` + +#### Signature + +```ts ignore +function isFloat16Array(it: unknown): it is Float16Array; +``` + +Check if the given value is a `Float16Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Float16Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isFloat16Array } from "jsr:@nick/is/float16array"; + +const arr = new Float16Array(8); +isFloat16Array(arr); // true +isFloat16Array(arr.buffer); // false +``` diff --git a/docs/float32-array.md b/docs/float32-array.md new file mode 100644 index 0000000..a733b25 --- /dev/null +++ b/docs/float32-array.md @@ -0,0 +1,35 @@ +# @nick/is/float32-array + +## `isFloat32Array` + +#### Signature + +```ts ignore +function isFloat32Array(it: unknown): it is Float32Array; +``` + +Check if the given value is a `Float32Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Float32Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isFloat32Array } from "jsr:@nick/is/float32array"; + +const arr = new Float32Array(8); +isFloat32Array(arr); // true +isFloat32Array(arr.buffer); // false +``` diff --git a/docs/float64-array.md b/docs/float64-array.md new file mode 100644 index 0000000..a737c47 --- /dev/null +++ b/docs/float64-array.md @@ -0,0 +1,35 @@ +# @nick/is/float64-array + +## `isFloat64Array` + +#### Signature + +```ts ignore +function isFloat64Array(it: unknown): it is Float64Array; +``` + +Check if the given value is a `Float64Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Float64Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isFloat64Array } from "jsr:@nick/is/float64array"; + +const arr = new Float64Array(8); +isFloat64Array(arr); // true +isFloat64Array(arr.buffer); // false +``` diff --git a/docs/function.md b/docs/function.md new file mode 100644 index 0000000..7e5906b --- /dev/null +++ b/docs/function.md @@ -0,0 +1,130 @@ +# @nick/is/function + +## `isFunction` + +#### Signature + +```ts ignore +function isFunction( + it: T | unknowns, +): it is FunctionOrConstructor extends T ? Function : T; +``` + +Check if the given value is a function. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a function, `false` otherwise. + +###### Category + +`Standard` + +#### Examples + +```ts +import { isFunction } from "jsr:@nick/is/function"; + +console.log(isFunction(() => {})); // true +console.log(isFunction(function () {})); // true +console.log(isFunction(class {})); // true +console.log(isFunction(new Function())); // true +console.log(isFunction({})); // false +console.log(isFunction(1)); // false +``` + +## `isFunction` + +#### Signature + +```ts ignore +function isFunction( + it: Fn | unknowns, +): it is Fn; +``` + +## `isFunction` + +#### Signature + +```ts ignore +function isFunction( + it: ThisFn | unknowns, +): it is ThisFn; +``` + +## `isFunction` + +#### Signature + +```ts ignore +function isFunction(it: unknown): it is Function; +``` + +## `isFunction` + +#### Signature + +```ts ignore +function isFunction(it: unknown): it is FunctionOrConstructor; +``` + +## `Fn` + +#### Signature + +```ts ignore +export type Fn = (...args: A) => T; +``` + +##### Type Parameters + +- **`T`** (default: `any`) +- **`A`** extends `readonly any[]` (default: `any[]`) + +--- + +## `FunctionOrConstructor` + +#### Signature + +```ts ignore +export type FunctionOrConstructor< + T = any, + A extends readonly any[] = any[], + R = void, +> = Constructor | Fn | ThisFn | Function; +``` + +##### Type Parameters + +- **`T`** (default: `any`) +- **`A`** extends `readonly any[]` (default: `any[]`) +- **`R`** (default: `void`) + +--- + +## `ThisFn` + +#### Signature + +```ts ignore +export type ThisFn = ( + this: T, + ...args: A +) => R; +``` + +##### Type Parameters + +- **`T`** (default: `any`) +- **`A`** extends `readonly any[]` (default: `any[]`) +- **`R`** (default: `any`) + +--- diff --git a/docs/generator-function.md b/docs/generator-function.md new file mode 100644 index 0000000..b435486 --- /dev/null +++ b/docs/generator-function.md @@ -0,0 +1,95 @@ +# @nick/is/generator-function + +## `isGeneratorFunction` + +#### Signature + +```ts ignore +function isGeneratorFunction(it: unknown): it is GeneratorFunction; +``` + +Checks if a given value is a generator function, which is a function that uses a +distinct syntax and returns a generator object when called. + +To check if a value is a generator object (the actual iterable iterator that is +typically used within `for..of` loops), use +[isGenerator](#isgenerator "Jump to symbol: 'isGenerator'") instead. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a generator function, `false` otherwise. + +###### Category + +`Generators` + +#### Examples + +```ts +import { isGeneratorFunction } from "jsr:@nick/is/generator-function"; + +function* gen() { + yield 1; +} +const iter = gen(); + +console.log(isGeneratorFunction(gen)); // true +console.log(isGeneratorFunction(iter)); // false +``` + +Another example, highlighting the differences between a generator function and a +generator object, using a custom iterable class: + +```ts +import { isGenerator, isGeneratorFunction, isIterable } from "jsr:@nick/is"; + +class Foo { + *delegate() { + return yield* this; // <- thanks to the [Symbol.iterator] method below + } + + *[Symbol.iterator](): IterableIterator { + for (let i = 0; i < 10; i++) yield i; + } +} + +const foo = new Foo(); + +// Since Foo.prototype has a [Symbol.iterator] method, it is iterable: +if (isIterable(foo)) { + // This will log the numbers 1 through 10 + for (const value of foo) console.log(value); +} + +// However, it is _not_ a generator not generator function: +isGenerator(foo); // false +isGeneratorFunction(foo); // false + +// It's delegate and [Symbol.iterator] methods _are_ generator functions: +isGeneratorFunction(foo.delegate); // true +isGeneratorFunction(foo[Symbol.iterator]); // true + +// And they _return_ generator objects...: +const iter1 = foo.delegate(); +const iter2 = foo[Symbol.iterator](); +isGenerator(iter1); // true +isGenerator(iter2); // true + +// ...which are also iterable: +isIterable(iter1); // true +isIterable(iter2); // true +``` + +#### Notes + +This function will **_not_** return `true` for async generator functions, as +they are a distinctly different type of function that returns a different type +of object. Use +[isAsyncGeneratorFunction](#isasyncgeneratorfunction "Jump to symbol: 'isAsyncGeneratorFunction'") +to check for an async generator function instead. diff --git a/docs/generator.md b/docs/generator.md new file mode 100644 index 0000000..370a683 --- /dev/null +++ b/docs/generator.md @@ -0,0 +1,46 @@ +# @nick/is/generator + +## `isGenerator` + +#### Signature + +```ts ignore +function isGenerator( + it: unknown, +): it is Generator; +``` + +Check if the given value is a generator, which is an iterable iterator that was +created with the `function*() { ... }` syntax. + +This is the type of value **_returned_** when a generator function +(`function*() { ... }`) is called, and not the type of the function itself. To +check for the function itself, use `isGeneratorFunction` instead. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a generator, `false` otherwise. + +###### Category + +`Generators` + +#### Examples + +```ts +import { isGenerator } from "jsr:@nick/is/generator"; + +function* gen() { + yield 1; +} +const iter = gen(); + +console.log(isGenerator(iter)); // true +console.log(isGenerator(gen)); // false +``` diff --git a/docs/has-methods.md b/docs/has-methods.md new file mode 100644 index 0000000..f4b68fc --- /dev/null +++ b/docs/has-methods.md @@ -0,0 +1,84 @@ +# @nick/is/has-methods + +## `hasMethods` + +#### Signature + +```ts ignore +function hasMethods(it: T, ...keys: K): it is Extract; +``` + +Checks if the given value contains methods for all of the specified keys. No +other properties or traits are checked by this guard, such that the target value +may be even be a primitive value like a string or number. + +##### Parameters + +| Name | Info | +| :--------- | :--------------------- | +| **`it`** | The object to check. | +| **`keys`** | The keys to check for. | + +##### Returns + +`true` if the object has all the specified keys, and each key is a callable +method; otherwise, `false`. + +###### Category + +`Guards` + +#### Examples + +```ts +import { hasMethods } from "@nick/is/has-methods"; + +const obj = { foo: () => "foo", bar: () => "bar", baz: 42 }; + +console.assert(hasMethods(obj, "foo", "bar")); // OK +``` + +```ts +import { hasMethods } from "@nick/is/has-methods"; + +const ab = new ArrayBuffer(8); + +console.assert(hasMethods(ab, "slice")); // OK + +// checking if resizable array buffer methods are available +if (hasMethods(ab, "resize", "transfer")) { + console.log("Great news - the RAB proposal is supported!"); +} +``` + +## `hasMethods` + +#### Signature + +```ts ignore +function hasMethods( + it: unknown, + ...keys: K +): it is { + [P in undefined]: Fn; +}; +``` + +## `hasMethods` + +#### Signature + +```ts ignore +function hasMethods(it: unknown, ...keys: PropertyKey[]): boolean; +``` + +## `hasMethods` + +#### Signature + +```ts ignore +function hasMethods(it: unknown, ...keys: PropertyKey[]): boolean; +``` diff --git a/docs/identifier.md b/docs/identifier.md new file mode 100644 index 0000000..569fcb6 --- /dev/null +++ b/docs/identifier.md @@ -0,0 +1,148 @@ +# @nick/is/identifier + +## `isIdentifier` + +#### Signature + +```ts ignore +function isIdentifier(it: T): it is Identifier; +``` + +Checks if a given string is a valid JavaScript identifier, meaning it can be +used as the name of a variable, function, property, label, or export. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a valid identifier, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isIdentifier } from "jsr:@nick/is/identifier"; + +console.log(isIdentifier("a")); // true +console.log(isIdentifier("1")); // false +console.log(isIdentifier("export")); // false +``` + +## `isIdentifier` + +#### Signature + +```ts ignore +function isIdentifier(it: unknown): it is Identifier; +``` + +Checks if a given value is a valid JavaScript identifier, meaning it can be used +as the name of a variable, function, property, label, or export. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a valid identifier, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isIdentifier } from "jsr:@nick/is/identifier"; + +console.log(isIdentifier("a")); // true +console.log(isIdentifier("1")); // false +console.log(isIdentifier("export")); // false +``` + +## `isIdentifier` + +#### Signature + +```ts ignore +function isIdentifier(it: unknown): it is Identifier; +``` + +Checks if a given value is a valid JavaScript identifier, meaning it can be used +as the name of a variable, function, property, label, or export. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a valid identifier, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isIdentifier } from "jsr:@nick/is/identifier"; + +console.log(isIdentifier("a")); // true +console.log(isIdentifier("1")); // false +console.log(isIdentifier("exportm z=-0fdxz")); // true +``` + +## `Identifier` + +#### Signature + +```ts ignore +export type Identifier = Brand; +``` + +Utility type brand that represents a valid JavaScript identifier. This is a +string that can be used as a name of a variable, function, property, label, or +export. It is a subtype of `string` and is used to distinguish between regular +strings and identifiers. + +##### Type Parameters + +- **`T`** extends `string` (default: `string`) + +--- + +###### Category + +`Primitives` + +## `ReservedWord` + +#### Signature + +```ts ignore +export type ReservedWord = reserved[number]; +``` + +Represents a reserved word in JavaScript that cannot be used as an identifier, +such as `export`, `default`, `class`, etc. + +###### Category + +`Primitives` + +###### Tags + +`identifier` `reserved` diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..58c09a5 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,54 @@ +--- +layout: home + +hero: + name: "@nick/is" + text: "Platform-agnostic, performant, and portable." + tagline: 160+ dependency-free type guards for all + actions: + - theme: brand + text: API + link: /api + - theme: alt + text: Examples + link: /examples + +features: + - title: "Portable" + icon: + description: | + Compatible with Deno, Bun, Node, Cloudflare Workers, and modern browsers. + Designed using standard ECMAScript APIs available on all major runtimes. + + - title: "Secure" + icon: + description: | + Zero dependencies. All predicates are hardened against prototype pollution + and context issues commonly encountered with the `instanceof` operator. + + - title: "Tree-shakeable" + icon: "heroicons:mini-trash" + description: | + Isolated submodules for each predicate, allowing your bundler to easily + eliminate unused code paths, so you only ship the code you actually use. + + - title: "Thoroughly Tested" + icon: "heroicons:mini-check-circle" + description: | + 160+ predicates with close to 100% coverage, from over 500 unit tests. + + - title: "Fully Documented" + icon: "heroicons:mini-book-open" + description: | + Each predicate is documented with examples and meaningful descriptions + to help you grasp the exact purpose and usage of every single function. + + - title: "Really Fucking Fast" + icon: "heroicons:mini-lightning-bolt" + description: | + Benchmarked against other libraries, like [lodash] and [underscore], to + ensure that you're getting the best performance possible for your use case. + + [lodash]: https://lodash.com + [underscore]: https://underscorejs.org +--- diff --git a/docs/instance.md b/docs/instance.md new file mode 100644 index 0000000..c56d267 --- /dev/null +++ b/docs/instance.md @@ -0,0 +1,86 @@ +# @nick/is/instance + +## `isInstance` + +#### Signature + +```ts ignore +function isInstance(it: unknown, constructor: Constructor): it is T; +``` + +Checks if a given value is an instance of a specific class or constructor. + +This is a type guard function that can be used to determine if a value is an +instance of a class or constructor function, even if the class is not directly +accessible in the current scope. + +##### Parameters + +| Name | Info | +| :---------------- | :-------------------------------------------------- | +| **`it`** | The value to check. | +| **`constructor`** | The class or constructor function to check against. | + +##### Returns + +`true` if it is an instance of the class; otherwise, `false`. + +###### Category + +`Guards` + +## `isInstance` + +#### Signature + +```ts ignore +function isInstance>( + it: unknown, + constructor: T, +): it is InstanceType; +``` + +Checks if a given value is an instance of a particular class or constructor. + +##### Parameters + +| Name | Info | +| :---------------- | :-------------------------------------------------- | +| **`it`** | The value to check. | +| **`constructor`** | The class or constructor function to check against. | + +##### Returns + +`true` if it is an instance of the class; otherwise, `false`. + +###### Category + +`Guards` + +## `isInstance` + +#### Signature + +```ts ignore +function isInstance, P = InstanceType>( + it: unknown, + constructor: T | Constructor

| P, +): it is InstanceType; +``` + +Checks if a given value is an instance of a specific class or constructor. + +##### Parameters + +| Name | Info | +| :---------------- | :-------------------------------------------------- | +| **`it`** | The value to check. | +| **`constructor`** | The class or constructor function to check against. | + +##### Returns + +`true` if it is an instance of the class; otherwise, `false`. + +###### Category + +`Guards` diff --git a/docs/int16-array.md b/docs/int16-array.md new file mode 100644 index 0000000..7e74af5 --- /dev/null +++ b/docs/int16-array.md @@ -0,0 +1,35 @@ +# @nick/is/int16-array + +## `isInt16Array` + +#### Signature + +```ts ignore +function isInt16Array(it: unknown): it is Int16Array; +``` + +Check if the given value is a `Int16Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Int16Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isInt16Array } from "jsr:@nick/is/int16array"; + +const arr = new Int16Array(8); +isInt16Array(arr); // true +isInt16Array(arr.buffer); // false +``` diff --git a/docs/int32-array.md b/docs/int32-array.md new file mode 100644 index 0000000..69ee066 --- /dev/null +++ b/docs/int32-array.md @@ -0,0 +1,35 @@ +# @nick/is/int32-array + +## `isInt32Array` + +#### Signature + +```ts ignore +function isInt32Array(it: unknown): it is Int32Array; +``` + +Check if the given value is a `Int32Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Int32Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isInt32Array } from "jsr:@nick/is/int32array"; + +const arr = new Int32Array(8); +isInt32Array(arr); // true +isInt32Array(arr.buffer); // false +``` diff --git a/docs/int8-array.md b/docs/int8-array.md new file mode 100644 index 0000000..dde67aa --- /dev/null +++ b/docs/int8-array.md @@ -0,0 +1,35 @@ +# @nick/is/int8-array + +## `isInt8Array` + +#### Signature + +```ts ignore +function isInt8Array(it: unknown): it is Int8Array; +``` + +Check if the given value is a `Int8Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Int8Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isInt8Array } from "jsr:@nick/is/int8array"; + +const arr = new Int8Array(8); +isInt8Array(arr); // true +isInt8Array(arr.buffer); // false +``` diff --git a/docs/iterable-iterator.md b/docs/iterable-iterator.md new file mode 100644 index 0000000..7207d1f --- /dev/null +++ b/docs/iterable-iterator.md @@ -0,0 +1,37 @@ +# @nick/is/iterable-iterator + +## `isIterableIterator` + +#### Signature + +```ts ignore +function isIterableIterator(it: unknown): it is IterableIterator; +``` + +Checks if a given value is an `IterableIterator`, which is an iterator object +that also has a `Symbol.iterator` method that returns a reference to itself. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `IterableIterator`, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isIterableIterator } from "jsr:@nick/is/iterable-iterator"; + +const iter = [1, 2][Symbol.iterator](); // Array iterator +console.log(isIterableIterator(iter)); // true +console.log(isIterableIterator(iter[Symbol.iterator]())); // true +console.log(isIterableIterator("foo"[Symbol.iterator]())); // false +``` diff --git a/docs/iterable-object.md b/docs/iterable-object.md new file mode 100644 index 0000000..4fb91c8 --- /dev/null +++ b/docs/iterable-object.md @@ -0,0 +1,62 @@ +# @nick/is/iterable-object + +## `isIterableObject` + +#### Signature + +```ts ignore +function isIterableObject(it: unknown): it is IterableObject; +``` + +Checks if a given value is an iterable object. This includes arrays, maps, and +sets, but not strings or other non-object iterables. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an iterable object, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isIterableObject } from "jsr:@nick/is/iterable-object"; + +console.log(isIterableObject([1, 2])); // true +console.log(isIterableObject(new Map())); // true +console.log(isIterableObject(new Set())); // true +console.log(isIterableObject({ [Symbol.iterator]: () => {} })); // true +console.log(isIterableObject("foo")); // false +``` + +## `IterableObject` + +#### Signature + +```ts ignore +export type IterableObject = Iterable & object; +``` + +Represents an object that is also an iterable. This is the type of arrays, maps, +sets, and objects with a Symbol.iterator method. It is a subtype of both +`Iterable` and `object`. This is also the type that the function +[isIterableObject](#isiterableobject "Jump to symbol: 'isIterableObject'") +narrows its inputs to. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +###### Category + +`Iterables` diff --git a/docs/iterable.md b/docs/iterable.md new file mode 100644 index 0000000..f65856a --- /dev/null +++ b/docs/iterable.md @@ -0,0 +1,40 @@ +# @nick/is/iterable + +## `isIterable` + +#### Signature + +```ts ignore +function isIterable(it: unknown): it is Iterable; +``` + +Checks if a given value is an iterable. This includes arrays, strings, maps, +sets, and any other value with a `Symbol.iterator` method. If you need to check +for iterable objects specifically, use `isIterableObject`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an iterable, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isIterable } from "jsr:@nick/is/iterable"; + +console.log(isIterable([1, 2])); // true +console.log(isIterable("foo")); // true +console.log(isIterable(new Map())); // true +console.log(isIterable(new Set())); // true +console.log(isIterable({ [Symbol.iterator]: () => {} })); // true +console.log(isIterable({})); // false +``` diff --git a/docs/iterator.md b/docs/iterator.md new file mode 100644 index 0000000..702005b --- /dev/null +++ b/docs/iterator.md @@ -0,0 +1,37 @@ +# @nick/is/iterator + +## `isIterator` + +#### Signature + +```ts ignore +function isIterator(it: unknown): it is Iterator; +``` + +Check if the given value is an iterator object. This includes arrays, maps, +sets, and any other value with a `.next` method. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an iterator, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isIterator } from "jsr:@nick/is/iterator"; + +const iterable = [1, 2, 3]; +const iterator = iterable[Symbol.iterator](); +console.log(isIterator(iterator)); // true +console.log(isIterator(iterable)); // false +``` diff --git a/docs/keyof.md b/docs/keyof.md new file mode 100644 index 0000000..cbf55a3 --- /dev/null +++ b/docs/keyof.md @@ -0,0 +1,29 @@ +# @nick/is/keyof + +## `isKeyOf` + +#### Signature + +```ts ignore +function isKeyOf( + o: T, + k: K, +): k is K & keyof T; +``` + +###### Category + +`Objects` + +#### Examples + +```ts +import { isKeyOf } from "jsr:@nick/is/keyof"; + +const obj = { a: 1, b: 2, c: 3 }; + +console.log(isKeyOf(obj, "a")); // true +console.log(isKeyOf(obj, "b")); // true +console.log(isKeyOf(obj, "c")); // true +console.log(isKeyOf(obj, "d")); // false +``` diff --git a/docs/map-iterator.md b/docs/map-iterator.md new file mode 100644 index 0000000..87fd2bc --- /dev/null +++ b/docs/map-iterator.md @@ -0,0 +1,61 @@ +# @nick/is/map-iterator + +## `isMapIterator` + +#### Signature + +```ts ignore +function isMapIterator(it: unknown): it is MapIterator; +``` + +Check if the given value is a map iterator, which is an iterable iterator that +yields key-value pairs from a Map object. This is the type of object returned by +the `Map.prototype.entries` and `Map.prototype[Symbol.iterator]` methods. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a map iterator, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isMapIterator } from "jsr:@nick/is/map-iterator"; + +const map = new Map([["foo", 1], ["bar", 2]]); +const iterator = map.entries(); +console.log(isMapIterator(iterator)); // true +console.log(isMapIterator(map)); // false +``` + +## `MapIterator` + +Represents a map iterator. + +##### Type Parameters + +- **`K`** +- **`V`** + +--- + +##### Extends `IterableIterator<[K,V]>` + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "Map Iterator" | "Map Entries"; +``` + +--- diff --git a/docs/map-like.md b/docs/map-like.md new file mode 100644 index 0000000..974a774 --- /dev/null +++ b/docs/map-like.md @@ -0,0 +1,249 @@ +# @nick/is/map-like + +## `isMapLike` + +#### Signature + +```ts ignore +function isMapLike(it: unknown): it is MapLike; +``` + +Checks whether a given value is a +[`MapLike`](#maplike "Jump to symbol: 'MapLike'") object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `MapLike` object; otherwise, `false`. + +## `isMapLikeConstructor` + +#### Signature + +```ts ignore +function isMapLikeConstructor(it: unknown): it is MapLikeConstructor; +``` + +Checks whether a given value is a +[`MapLikeConstructor`](#maplikeconstructor "Jump to symbol: 'MapLikeConstructor'") +function, which is defined as a constructor function with a `prototype` property +that appears to be a [`MapLike`](#maplike "Jump to symbol: 'MapLike'") object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a +[`MapLikeConstructor`](#maplikeconstructor "Jump to symbol: 'MapLikeConstructor'"); +otherwise, `false`. + +###### Category + +`Guards` + +## `MapLike` + +Map-like objects are collections of keys and values, where each key may only +appear once in the collection. + +###### Category + +`Types` + +##### Type Parameters + +- **`K`** +- **`V`** + +--- + +##### Extends `Iterable<[K,V]>` + +### Properties + +#### size + +```ts +readonly size: number; +``` + +Gets the number of elements in the collection. + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: string; +``` + +--- + +### Methods + +#### has + +```ts +has(key: K): boolean; +``` + +Tests whether a key is present in the collection. + +##### Parameters + +| Name | Info | +| :-------- | :----------------- | +| **`key`** | The key to lookup. | + +##### Returns + +`true` if the key is present in the collection; otherwise, `false`. + +#### get + +```ts +get(key: K): V | undefined; +``` + +Gets the value associated with the provided key, if it exists. + +##### Parameters + +| Name | Info | +| :-------- | :----------------- | +| **`key`** | The key to lookup. | + +##### Returns + +The value associated with the provided key, or `undefined`. + +#### set + +```ts +set(key: K, value: V): this; +``` + +Sets the value in the collection associated with the provided key. + +##### Parameters + +| Name | Info | +| :---------- | :---------------- | +| **`key`** | The key to set. | +| **`value`** | The value to set. | + +##### Returns + +The collection. + +#### clear + +```ts +clear(): void; +``` + +Removes all entries from the collection. + +#### delete + +```ts +delete(key: K): boolean; +``` + +Removes a key from the collection. + +##### Parameters + +| Name | Info | +| :-------- | :----------------- | +| **`key`** | The key to remove. | + +##### Returns + +`true` if the delete operation was successful, otherwise `false`. + +#### keys + +```ts +keys(): IterableIterator; +``` + +Returns an `IterableIterator` for the keys present in the collection. + +#### values + +```ts +values(): IterableIterator; +``` + +Returns an `IterableIterator` for the values present in the collection. + +#### entries + +```ts +entries(): IterableIterator< + [K, V] + >; +``` + +Returns an `IterableIterator` for the entries present in the collection. Each +entry is a tuple containing the key and value for each element. + +#### forEach + +```ts +forEach( + cb: (this: This, value: V, key: K, map: MapLike) => void, + thisArg?: This, + ): void; +``` + +Executes a provided function once per each key/value pair in the collection. + +##### Parameters + +| Name | Info | +| :------------ | :------------------------------------------------------ | +| **`cb`** | The callback to execute. | +| **`thisArg`** | The value to use as `this` when executing the callback. | + +##### Returns + +Nothing. + +#### [Symbol.iterator] + +```ts +[Symbol.iterator](): IterableIterator< + [K, V] + >; +``` + +Returns an `IterableIterator` for the entries present in the collection. + +--- + +## `MapLikeConstructor` + +A constructor function for creating new `MapLike` objects. + +###### Category + +`Types` + +### Properties + +#### prototype + +```ts +readonly prototype: MapLike; +``` + +--- diff --git a/docs/map.md b/docs/map.md new file mode 100644 index 0000000..708e004 --- /dev/null +++ b/docs/map.md @@ -0,0 +1,51 @@ +# @nick/is/map + +## `isMap` + +#### Signature + +```ts ignore +function isMap(it: unknown): it is Map; +``` + +Checks if a given value is a `Map` instance. This is a more reliable check than +`it instanceof Map` because it works across different realms, and it does not +require the `Map` constructor to be the same as the one in the current +environment that the code is running in. + +It also is more strict than `it instanceof Map`, and does not consider any +objects created via `Object.create(Map.prototype)` (or similar constructs) as +valid `Map` instances, while they would pass the `instanceof` check. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Map` instance, `false` otherwise. + +###### Category + +`Keyed Collections` + +#### Examples + +```ts +import { isMap } from "jsr:@nick/is/map"; + +isMap(new Map()); // true +isMap(new WeakMap()); // false +isMap({}); // false +isMap(new Set()); // false +``` + +```ts +import { isMap } from "jsr:@nick/is/map"; + +const fakeMap = Object.create(Map.prototype); +console.log(isMap(fakeMap)); // false +console.log(fakeMap instanceof Map); // true (?!) +``` diff --git a/docs/missing.md b/docs/missing.md new file mode 100644 index 0000000..da2cf5f --- /dev/null +++ b/docs/missing.md @@ -0,0 +1,37 @@ +# @nick/is/missing + +## `isMissing` + +#### Signature + +```ts ignore +function isMissing(it: unknown): it is null | undefined; +``` + +Check if a given value is missing, which is either `null` or `undefined`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `null` or `undefined`, or `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isMissing } from "jsr:@nick/is/missing"; + +isMissing(null); // true +isMissing(undefined); // true +isMissing(0); // false +isMissing(""); // false +isMissing(false); // false +``` diff --git a/docs/namespace.md b/docs/namespace.md new file mode 100644 index 0000000..0c27544 --- /dev/null +++ b/docs/namespace.md @@ -0,0 +1,13399 @@ +# @nick/is/namespace + +## `arguments` + +#### Signature + +```ts ignore +function arguments(it: unknown): it is IArguments; +``` + +Check if the given value is an instance of the native `Arguments` object, which +is a special type of Array-like object that corresponds to the binding arguments +of a particular JavaScript function. + +This check will return `false` for any other kind of array-like object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `Arguments` object, `false` otherwise. + +###### Category + +`Indexed Collections` + +#### Examples + +```ts +import { isArguments } from "jsr:@nick/is/arguments"; + +function foo() { + console.log(isArguments(arguments)); // true + console.log(isArguments([1, 2, 3])); // false +} +``` + +## `array` + +#### Signature + +```ts ignore +function array(a: unknown, test?: Predicate): a is T[]; +``` + +Checks if the given value is an array, optionally verifying that each of its +elements are of a specific type. + +##### Parameters + +| Name | Info | +| :--------- | :------------------------------------------------------ | +| **`it`** | The value to check. | +| **`test`** | The type guard to check the type of the array elements. | + +##### Returns + +`true` if it is an array, and the predicate (if provided) is satisfied by each +of its values. Otherwise, returns `false`. + +###### Category + +`Indexed Collections` + +#### Examples + +```ts +import { isArray, isNumber, isString } from "jsr:@nick/is"; +import { expectType } from "jsr:@nick/is/type/expect"; + +const arr: unknown[] = ["a", "b", "c"]; + +if (isArray(arr, isString)) { + console.log(arr, "is an array of strings"); + // ^? const arr: string[] + expectType(arr); +} else if (isArray(arr, isNumber)) { + console.log(arr, "is an array of numbers"); + // ^? const arr: number[] + expectType(arr); +} else { + console.log(arr, "is not an array of strings or numbers"); + // ^? const arr: unknown[] + expectType(arr); +} +``` + +## `arrayBuffer` + +#### Signature + +```ts ignore +function arrayBuffer(it: unknown): it is ArrayBuffer; +``` + +Returns `true` if [`it`](#it "Jump to symbol: 'it'") is an `ArrayBuffer`. This +does not include instances of the `SharedArrayBuffer`, which has its own type +guard. To check for either type, use +[`isArrayBufferLike`](#isarraybufferlike "Jump to symbol: 'isArrayBufferLike'"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `ArrayBuffer`, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isArrayBuffer } from "jsr:@nick/is/array-buffer"; + +const buffer = new ArrayBuffer(8); +const shared = new SharedArrayBuffer(8); +const array = new Uint8Array(buffer); + +isArrayBuffer(buffer); // true +isArrayBuffer(shared); // false +isArrayBuffer(array); // false +isArrayBuffer(array.buffer); // true +``` + +## `arrayBufferLike` + +#### Signature + +```ts ignore +function arrayBufferLike(it: unknown): it is ArrayBufferLike; +``` + +Checks if [`it`](#it "Jump to symbol: 'it'") is an `ArrayBuffer` or a +`SharedArrayBuffer`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `ArrayBuffer` or a `SharedArrayBuffer`, or `false` +otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isArrayBufferLike } from "jsr:@nick/is/any-array-buffer"; + +const buffer = new ArrayBuffer(8); +const shared = new SharedArrayBuffer(8); +const array = new Uint8Array(buffer); + +isArrayBufferLike(buffer); // true +isArrayBufferLike(shared); // true +isArrayBufferLike(array); // false +isArrayBufferLike(array.buffer); // true +``` + +## `arrayBufferView` + +#### Signature + +```ts ignore +function arrayBufferView(it: unknown): it is ArrayBufferView; +``` + +Checks if a value is an `ArrayBufferView`, which includes all typed arrays and +`DataView` objects, but not `ArrayBuffer` or `SharedArrayBuffer`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `ArrayBufferView`, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isArrayBufferView } from "jsr:@nick/is/array-buffer-view"; + +const buffer = new ArrayBuffer(8); +const view = new DataView(buffer); +const array = new Uint8Array(buffer); + +isArrayBufferView(buffer); // false +isArrayBufferView(view); // true +isArrayBufferView(array); // true +``` + +## `arrayIterator` + +#### Signature + +```ts ignore +function arrayIterator(it: unknown): it is ArrayIterator; +``` + +Check if the given value is an array iterator, which is an iterable iterator +that yields key-value pairs from an Array. This is the type of value that is +returned by `Array.prototype.values` and `Array.prototype[Symbol.iterator]`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a array iterator, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isArrayIterator } from "jsr:@nick/is/array-iterator"; + +const array = ["foo", "bar", "foo"]; +const iter = array[Symbol.iterator](); +console.log(isArrayIterator(iterator)); // true +console.log(isArrayIterator(array)); // false +``` + +## `arrayLike` + +#### Signature + +```ts ignore +function arrayLike(it: unknown): it is ArrayLike; +``` + +Checks if a given value is `ArrayLike`, which is defined as +`any +non-function value with an own property named 'length' that is an integer, +and where 'length' >= '0' and <= 'Number.MAX_SAFE_INTEGER'`. + +This condition includes strings. If you'd like to check specifically for +`ArrayLike` _objects_, see +[`isArrayLikeObject`](#isarraylikeobject "Jump to symbol: 'isArrayLikeObject'") +instead. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if it is an ArrayLike value + +###### Category + +`Indexed Collections` + +#### Examples + +```ts +import { isArrayLike } from "jsr:@nick/is/array-like"; + +isArrayLike([]); // true +isArrayLike("abc"); // true +isArrayLike({ length: 0 }); // true +isArrayLike({ length: 1, 0: "a" }); // true +isArrayLike({ length: Infinity }); // false +isArrayLike({ length: -1 }); // false +``` + +## `arrayLikeObject` + +#### Signature + +```ts ignore +function arrayLikeObject(it: unknown): it is ArrayLikeObject; +``` + +Checks if a given value is an `ArrayLike` object. This is a stricter form of the +[`isArrayLike`](#isarraylike "Jump to symbol: 'isArrayLike'") check that only +returns `true` if a value is an **_object_** that also meets all of the +`ArrayLike` conditions: + +- it is not a function +- it has an own property named `length` that is a finite unsigned integer: + - an integer between `0` and `Number.MAX_SAFE_INTEGER` + - it is non-negative, `NaN`, `Infinity`, nor `-Infinity` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an object that meets all of the `ArrayLike` conditions, +otherwise `false`. + +###### Category + +`Indexed Collections` + +###### See Also + +- [`isArrayLike`](#isarraylike "Jump to symbol: 'isArrayLike'") for a version + that allows for non-object values such as strings (but not functions). + +#### Examples + +```ts +import { isArrayLikeObject } from "jsr:@nick/is/array-like"; + +isArrayLikeObject([]); // true +isArrayLikeObject({ length: 0 }); // true +isArrayLikeObject({ length: 1, 0: "a" }); // true + +// strings are not considered ArrayLike objects +isArrayLikeObject("abc"); // false + +// length must be a finite unsigned integer +isArrayLikeObject({ length: Infinity }); // false + +// length must be non-negative +isArrayLikeObject({ length: -1 }); // false + +// length cannot be a non-number or NaN +isArrayLikeObject({ length: "a" }); // false +isArrayLikeObject({ length: NaN }); // false + +// functions are not considered ArrayLike objects, despite meeting the +// requirements for the 'length' property. this is because they are not +// indexed collections like an array or string. +isArrayLikeObject(() => {}); +``` + +## `asyncDisposable` + +#### Signature + +```ts ignore +function asyncDisposable(it: unknown): it is AsyncDisposable; +``` + +Checks if a value is an object that implements the `AsyncDisposable` API. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an object that implements the `AsyncDisposable` API, or +`false` otherwise. + +###### Category + +`Explicit Resource Management` + +#### Examples + +```ts +import { isAsyncDisposable } from "@nick/is/async_disposable"; + +const disposable = { + [Symbol.dispose]() { + return; + }, +}; + +const asyncDisposable = { + async [Symbol.asyncDispose]() { + await Promise.resolve(); + }, +}; + +isAsyncDisposable(disposable); // false +isAsyncDisposable(asyncDisposable); // true +``` + +## `asyncFunction` + +#### Signature + +```ts ignore +function asyncFunction(it: unknown): it is AsyncFunction; +``` + +## `asyncGenerator` + +#### Signature + +```ts ignore +function asyncGenerator( + it: unknown, +): it is AsyncGenerator; +``` + +Check if the given value is an async generator, which is an asynchronous +iterable iterator (`AsyncIterableIterator`) that was created using the +`async function*() { ... }` syntax. + +This is the type of value **_returned_** when an async generator function +(`async function*() {}`) is called. To check for the function itself, use +`isAsyncGeneratorFunction` instead. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an AsyncGenerator, `false` otherwise. + +###### Category + +`Generators` + +#### Examples + +```ts +import { isAsyncGenerator } from "jsr:@nick/is/async-generator"; + +async function* genFn() { + yield await Promise.resolve(1); +} +const gen = genFn(); + +console.log(isAsyncGenerator(gen)); // true +console.log(isAsyncGenerator(genFn)); // false +``` + +## `asyncGeneratorFunction` + +#### Signature + +```ts ignore +function asyncGeneratorFunction(it: unknown): it is AsyncGeneratorFunction; +``` + +Checks if a given value is an async generator function, which is a function that +returns an async generator object when called, and was created with the +`async function*() { ... }` syntax. + +To check if a value is an async generator object, use `isAsyncGenerator`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an async generator function, `false` otherwise. + +###### Category + +`Generators` + +#### Examples + +```ts +import { + isAsyncGeneratorFunction, +} from "jsr:@nick/is/async-generator-function"; + +const genFnAsync = async function* () { + yield 1; +}; +isAsyncGeneratorFunction(genFnAsync); // true + +const genObjAsync = genFnAsync(); +isAsyncGeneratorFunction(genObjAsync); // false + +const genFn = function* () { + yield 1; +}; +isAsyncGeneratorFunction(genFn); // false + +const genObj = genFn(); +isAsyncGeneratorFunction(genObj); // false +``` + +## `asyncIterable` + +#### Signature + +```ts ignore +function asyncIterable(it: unknown): it is AsyncIterable; +``` + +Checks if a given value is an object with a `Symbol.asyncIterator` method. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `AsyncIterable`, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isAsyncIterable } from "jsr:@nick/is/async-iterable"; + +const iter = (async function* () { + yield 1; +})(); +console.log(isAsyncIterable(iter)); // true +``` + +## `asyncIterableIterator` + +#### Signature + +```ts ignore +function asyncIterableIterator(it: unknown): it is AsyncIterableIterator; +``` + +Checks if a value is an `AsyncIterableIterator`, which is an `AsyncIterator` +with a `Symbol.asyncIterator` method that returns a reference to itself. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `AsyncIterableIterator`, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import isAsyncIterableIterator from "jsr:@nick/is/async-iterable-iterator"; + +const iter = (async function* () { + yield 1; +})(); +console.log(isAsyncIterableIterator(iter)); // true +console.log(isAsyncIterableIterator(iter[Symbol.asyncIterator]())); // true +``` + +## `asyncIterableObject` + +#### Signature + +```ts ignore +function asyncIterableObject(it: unknown): it is AsyncIterableObject; +``` + +Checks if a given value is an `AsyncIterable` object. + +Similar to its synchronous counterpart, `isIterableObject`, this function +requires the value to be a non-primitive (and non-null) object, and also +implement a `[Symbol.asyncIterator]` method as per the `AsyncIterable` API. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an iterable object, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isAsyncIterableObject } from "jsr:@nick/is/async-iterable-object"; + +// synchronous iterables will not pass +console.log(isAsyncIterableObject([1, 2])); // false +console.log(isAsyncIterableObject(new Map())); // false +console.log(isAsyncIterableObject(new Set())); // false + +// non-object iterables will not pass +console.log(isAsyncIterableObject("foo")); // false + +// only asynchronous iterable objects will pass +const iter = { + async *[Symbol.asyncIterator]() { + yield await Promise.resolve(1); + }, +}; +console.log(isAsyncIterableObject(iter)); // true +``` + +```ts +import { isAsyncIterableObject } from "jsr:@nick/is/async-iterable-object"; + +const kv = await Deno.openKv(); +console.log(isAsyncIterableObject(kv)); // false + +const iter = kv.list({ prefix: [] }); +console.log(isAsyncIterableObject(iter)); // true + +kv.close(); +``` + +## `asyncIterator` + +#### Signature + +```ts ignore +function asyncIterator(it: unknown): it is AsyncIterator; +``` + +Check if the given value is an async iterator, which is an object that has a +`"next"` method that returns a promise for an iterator result. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an async iterator, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isAsyncIterator } from "jsr:@nick/is/async-iterator"; + +const iter = (async function* () { + yield 1; +})(); +console.log(isAsyncIterator(iter)); // true +console.log(isAsyncIterator(iter[Symbol.asyncIterator]())); // true +``` + +## `bigint` + +#### Signature + +```ts ignore +function bigint(it: unknown): it is bigint; +``` + +Checks if the given value is a primitive bigint value. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a primitive bigint, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isBigInt } from "jsr:@nick/is/bigint"; + +const x: unknown = 123n; +if (isBigInt(x)) { + console.log(x + 1n); + // ^? const x: bigint +} +``` + +## `bigInt` + +#### Signature + +```ts ignore +function bigInt(it: unknown): it is bigint; +``` + +Checks if the given value is a primitive bigint value. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a primitive bigint, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isBigInt } from "jsr:@nick/is/bigint"; + +const x: unknown = 123n; +if (isBigInt(x)) { + console.log(x + 1n); + // ^? const x: bigint +} +``` + +## `bigInt64Array` + +#### Signature + +```ts ignore +function bigInt64Array(it: unknown): it is BigInt64Array; +``` + +Check if the given value is a `BigInt64Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `BigInt64Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isBigInt64Array } from "jsr:@nick/is/bigint64array"; + +const arr = new BigInt64Array(8); +isBigInt64Array(arr); // true +isBigInt64Array(arr.buffer); // false +``` + +## `bigintObject` + +#### Signature + +```ts ignore +function bigintObject(it: unknown): it is BigInt; +``` + +Checks if a value is a BigInt object, which is a boxed-primitive BigInt that was +created by wrapping a primitive BigInt (bigint) in the `Object()` wrapper +function. + +Boxed primitives are strongly discouraged in JavaScript, as they can lead to all +sorts of unexpected behavior and performance issues. As such, this function - +and the other boxed primitive functions like it - are provided for your +convenience, to help you easily ensure your code is not on the receiving end of +such behavior. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a boxed-primitive BigInt object; otherwise, `false`. + +###### Category + +`Boxed Primitives` + +#### Examples + +```ts +import { isBigIntObject } from "jsr:@nick/is/bigint-object"; + +isBigIntObject(Object(BigInt("2"))); // true + +isBigIntObject(BigInt("2")); // false +isBigIntObject(2n); // false +``` + +## `bigIntObject` + +#### Signature + +```ts ignore +function bigIntObject(it: unknown): it is BigInt; +``` + +Checks if a value is a BigInt object, which is a boxed-primitive BigInt that was +created by wrapping a primitive BigInt (bigint) in the `Object()` wrapper +function. + +Boxed primitives are strongly discouraged in JavaScript, as they can lead to all +sorts of unexpected behavior and performance issues. As such, this function - +and the other boxed primitive functions like it - are provided for your +convenience, to help you easily ensure your code is not on the receiving end of +such behavior. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a boxed-primitive BigInt object; otherwise, `false`. + +###### Category + +`Boxed Primitives` + +#### Examples + +```ts +import { isBigIntObject } from "jsr:@nick/is/bigint-object"; + +isBigIntObject(Object(BigInt("2"))); // true + +isBigIntObject(BigInt("2")); // false +isBigIntObject(2n); // false +``` + +## `bigUint64Array` + +#### Signature + +```ts ignore +function bigUint64Array(it: unknown): it is BigUint64Array; +``` + +Check if the given value is a `BigUint64Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `BigUint64Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isBigUint64Array } from "jsr:@nick/is/biguint64array"; + +const arr = new BigUint64Array(8); +isBigUint64Array(arr); // true +isBigUint64Array(arr.buffer); // false +``` + +## `boolean` + +#### Signature + +```ts ignore +function boolean(it: unknown): it is boolean; +``` + +Checks if the given value is a boolean. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a boolean, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isBoolean } from "jsr:@nick/is/boolean"; +isBoolean("true"); // false +isBoolean(true); // true +``` + +## `booleanObject` + +#### Signature + +```ts ignore +function booleanObject(it: unknown): it is Boolean; +``` + +Checks if a value is a Boolean object, which is a boxed-primitive boolean that +was created either with the `new Boolean()` syntax, or by wrapping a primitive +boolean in the `Object()` wrapper function. + +Boxed primitives are strongly discouraged in JavaScript, as they can lead to all +sorts of unexpected behavior and performance issues. As such, this function - +and the other boxed primitive functions like it - are provided for your +convenience, to help you easily ensure your code is not on the receiving end of +such behavior. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a boxed-primitive boolean object; otherwise, `false`. + +###### Category + +`Boxed Primitives` + +#### Examples + +```ts +import { isBooleanObject } from "jsr:@nick/is/boolean-object"; + +isBooleanObject(Object(true)); // true +isBooleanObject(new Boolean(true)); // true + +isBooleanObject(Boolean(true)); // false +isBooleanObject(true); // false +``` + +## `both` + +#### Signature + +```ts ignore +function both( + left: (it: any, ...args: any[]) => it is L, + right: (it: any, ...args: any[]) => it is R, +): (it: unknown) => it is L & R; +``` + +Combine two different predicates into one, such that the resulting function +returns `true` if a given input satisfies **both** of the two predicates. + +This creates a logical AND between the two predicates, narrowing types to an +intersection of the two original predicates' return types. This helps you +compose custom reusable type guards with ease, reducing boilerplate and +repetition. + +**Note**: just like in the rest of TypeScript code, if you attempt to use an +incompatible pair of predicates in this function, the resulting type it will +narrow to will probably be `never`. For this reason, don't use this function to +combine mutually exclusive predicates like `isString` and `isNumber`. + +##### Parameters + +| Name | Info | +| :---------- | :----------------------------- | +| **`left`** | The first predicate to check. | +| **`right`** | The second predicate to check. | + +##### Returns + +A new predicate that returns `true` if both +[left](#left "Jump to symbol: 'left'") and +[right](#right "Jump to symbol: 'right'") are satisfies by a given input. + +###### Category + +`Composition` + +#### Examples + +```ts +import { is, isBoth } from "@nick/is"; + +// creating a custom type guard by hand +const isEmpty = ( + it: T, +): it is T & { readonly length: 0 } => ( + "length" in Object(it) && Object(it).length === 0 +); + +// composing a custom type guard with `isBoth` +const isEmptyString = isBoth(is.string, isEmpty); +// ^? const isEmptyString: (it: unknown) => it is string & { readonly length: 0 } + +// using the custom type guard +isEmptyString(""); // true +isEmptyString("foo"); // false +isEmptyString([]); // false +``` + +## `boxedPrimitive` + +#### Signature + +```ts ignore +function boxedPrimitive( + it: T | {} | null | undefined, +): it is T; +``` + +Checks if a value is a boxed-primitive object, which is an object that was +created by wrapping a primitive value in the `Object()` wrapper function, or by +using the `new` operator with the `String`, `Number`, or `Boolean` constructors +(`Symbol` and `BigInt` do not support the `new` operator). + +Boxed primitives are strongly discouraged in JavaScript, as they can lead to all +sorts of unexpected behavior and performance issues. As such, this function - +and the other boxed primitive functions like it - are provided for your +convenience, to help you easily ensure your code is not on the receiving end of +such behavior. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a boxed-primitive object; otherwise, `false`. + +###### Category + +`Boxed Primitives` + +#### Examples + +```ts +import { isBoxedPrimitive } from "jsr:@nick/is/boxed-primitive"; + +isBoxedPrimitive(new String("abc")); // true +isBoxedPrimitive(new Number(42)); // true +isBoxedPrimitive(new Boolean(true)); // true + +isBoxedPrimitive("abc"); // false +isBoxedPrimitive(42); // false +isBoxedPrimitive(true); // false +``` + +## `boxedPrimitive` + +#### Signature + +```ts ignore +function boxedPrimitive(it: unknown): it is BoxedPrimitive; +``` + +## `boxedPrimitive` + +#### Signature + +```ts ignore +function boxedPrimitive(it: unknown): it is BoxedPrimitive; +``` + +## `bufferSource` + +#### Signature + +```ts ignore +function bufferSource(it: unknown): it is BufferSource; +``` + +Returns `true` if [`it`](#it "Jump to symbol: 'it'") is an `ArrayBuffer`, +`SharedArrayBuffer`, or an `ArrayBufferView`, which includes `TypedArray`s and +`DataView`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a BufferSource object, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isBufferSource } from "jsr:@nick/is/buffer-source"; + +const buffer = new ArrayBuffer(8); +const view = new DataView(buffer); +const array = new Uint8Array(buffer); + +isBufferSource(buffer); // true +isBufferSource(view); // true +isBufferSource(array); // true +``` + +## `class` + +#### Signature + +```ts ignore +function class>(it: unknown): it is Class; +``` + +Checks if a given value is a constructor function, also known as a class. + +This includes all **pure** functions - no generators, arrow functions, or +getters/setters - that also have an own `prototype` propertty which is a +non-null object. The prototype must have an own `constructor` property that +points back to the class constructor function itself. Lastly, the function's +source code is inspected for the `class` keyword, to ensure that it is a class +and not just a regular function. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a class, `false` otherwise. + +###### Category + +`Objects` + +#### Examples + +```ts +import { isClass } from "jsr:@nick/is/class"; + +class Foo {} +console.log(isClass(Foo)); // true + +const Bar = function () { + this.foo = "bar"; + return this; +}; +console.log(isClass(Bar)); // false + +const Baz = () => {}; +console.log(isClass(Baz)); // false +``` + +## `closer` + +#### Signature + +```ts ignore +function closer(it: unknown): it is Closer; +``` + +Checks if a given value implments the `Deno.Closer` interface, which means it +has a `close` method that can be called to release associated resources. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value implements `Deno.Closer`, `false` otherwise. + +###### Category + +`I/O` + +#### Examples + +```ts +import { isCloser } from "jsr:@nick/is/closer"; + +const file = await Deno.open("file.txt"); +isCloser(file); // true + +const socket = new WebSocket("ws://example.com"); +isCloser(socket); // true +``` + +## `constructor` + +#### Signature + +```ts ignore +function constructor(it: unknown): it is Constructor; +``` + +Checks whether a given value is a constructor function. + +In this context, a constructor is defined as a function with a `prototype` own +property that contains an object with an own `constructor` property that points +back to the constructor function itself. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a constructor function; otherwise, `false`. + +###### Category + +`Guards` + +#### Examples + +```ts +import { isConstructor } from "jsr:@nick/is/constructor"; + +class Foo {} +console.log(isConstructor(Foo)); // true +console.log(isConstructor(Foo.prototype.constructor)); // true +console.log(isConstructor(class {})); // true +console.log(isConstructor(function () {})); // true + +console.log(isConstructor({})); // false +console.log(isConstructor(null)); // false +console.log(isConstructor(Foo.prototype)); // false +console.log(isConstructor(() => new Foo())); // false +``` + +## `dataView` + +#### Signature + +```ts ignore +function dataView(it: unknown): it is DataView; +``` + +Checks if a given value is a `DataView`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `DataView`, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isDataView } from "jsr:@nick/is/data-view"; + +const buffer = new ArrayBuffer(8); +const view = new DataView(buffer); +console.log(isDataView(view)); // true +console.log(isDataView(buffer)); // false +``` + +## `date` + +#### Signature + +```ts ignore +function date(it: unknown): it is Date; +``` + +Checks if a given value is a `Date` instance. This is a more reliable check than +`it instanceof Date` because it also works across different realms. + +This only returns `true` for values that are valid `Date` instances, meaning +`Object.create(Date.prototype)` and similar constructs will return `false`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Date` instance, `false` otherwise. + +###### Category + +`Standard` + +#### Examples + +```ts +import { isDate } from "jsr:@nick/is/date"; + +isDate(new Date()); // true +isDate(new Date(0)); // true +isDate(new Date("2021-01-01")); // true +``` + +## `dateString` + +#### Signature + +```ts ignore +function dateString(it: unknown): it is DateString; +``` + +Checks if a given value is a valid date string. + +The term "date string" refers to any string that can be parsed by the native +`Date` constructor as-is, without the help of any external libraries or any +preparatory formatting. One of the most common formats is ISO 8601, which is +what the native `Date` constructor itself uses in the `toDateString()` and +`toISOString()` methods. + +Note: This function does not check if the date string is in a specific format +like ISO 8601. It only checks if the string can be parsed into a valid Date +instance. + +Values that fail to pass this check would be expected to result in `NaN` when +passed to the `Date` constructor and coerced to a primitive number (e.g. +`+new Date("2023-13-01")`). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a valid date string; otherwise, `false`. + +###### Category + +`Guards` + +#### Examples + +```ts +import { isDateString } from "@nick/is/date_string"; + +console.assert(isDateString("4/20/2024"), "it works!"); +console.assert(isDateString("2024-04-20"), "it works!"); +console.assert(isDateString("02.32.2025"), "wtf lol"); +``` + +## `defined` + +#### Signature + +```ts ignore +function defined(it: T | undefined): it is T; +``` + +Checks if a value is not `undefined`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is not `undefined`, or `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isDefined } from "jsr:@nick/is/defined"; + +isDefined(null); // true +isDefined(undefined); // false +isDefined(0); // true +isDefined(void 0); // false +isDefined(""); // true +``` + +```ts +import { isDefined } from "jsr:@nick/is/defined"; + +let value: number | undefined; +if (isDefined(value)) { + value += 1; + // ^? let value: number +} else { + value; + // ^? let value: undefined + value = 0; + // ^? let value: number | undefined +} +``` + +## `disposable` + +#### Signature + +```ts ignore +function disposable(it: unknown): it is Disposable; +``` + +Checks if a value is an object that implements the `Disposable` API. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an object that implements the `Disposable` API, or +`false` otherwise. + +###### Category + +`Explicit Resource Management` + +#### Examples + +```ts +import { isDisposable } from "@nick/is/disposable"; + +const disposable = { + [Symbol.dispose]() { + return; + }, +}; + +const asyncDisposable = { + async [Symbol.asyncDispose]() { + await Promise.resolve(); + }, +}; + +isDisposable(disposable); // true +isDisposable(asyncDisposable); // false +``` + +## `either` + +#### Signature + +```ts ignore +function either( + left: (it: any, ...args: any[]) => it is L, + right: (it: any, ...args: any[]) => it is R, +): (it: unknown) => it is L | R; +``` + +Combine two different predicates into one, such that the resulting function +returns `true` if a given input satisfies **either** of the two predicates. + +This creates a logical OR between the two predicates, narrowing types to a union +of the two original predicates' return types. This helps you compose custom +reusable type guards with ease, reducing boilerplate and repetition. + +##### Parameters + +| Name | Info | +| :---------- | :----------------------------- | +| **`left`** | The first predicate to check. | +| **`right`** | The second predicate to check. | + +##### Returns + +A new predicate that returns `true` if either +[left](#left "Jump to symbol: 'left'") or +[right](#right "Jump to symbol: 'right'") are satisfies by a given input. + +###### Category + +`Composition` + +#### Examples + +```ts +import { isEither, isString, isSymbol } from "@nick/is"; + +// creating a custom type guard that checks for strings or symbols +const isStringOrSymbol = isEither(isString, isSymbol); +// ^? const isStringOrSymbol: (it: unknown) => it is string | symbol + +// using the custom type guard +isStringOrSymbol("foo"); // true +isStringOrSymbol(Symbol.iterator); // true +isStringOrSymbol(123); // false +``` + +## `empty` + +#### Signature + +```ts ignore +function empty(it: string): it is ""; +``` + +Checks if a given value is an empty string. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an empty string, `false` otherwise. + +###### Category + +`Chain` + +#### Examples + +```ts +import { isEmpty } from "@nick/is/empty"; + +isEmpty(""); // true +isEmpty("a"); // false +``` + +## `empty` + +#### Signature + +```ts ignore +function empty(it: readonly unknown[]): it is readonly []; +``` + +Checks if a given value is an empty Array object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an empty Array object, `false` otherwise. + +###### Category + +`Chain` + +#### Examples + +```ts +import { isEmpty } from "@nick/is/empty"; + +isEmpty([]); // true +isEmpty([1]); // false +``` + +## `empty` + +#### Signature + +```ts ignore +function empty>(it: U): it is U & { + readonly length: 0; +}; +``` + +Checks if a given value is an empty ArrayLike object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an empty ArrayLike object, `false` otherwise. + +###### Category + +`Chain` + +#### Examples + +```ts +import { isEmpty } from "@nick/is/empty"; + +isEmpty([]); // true +isEmpty([1]); // false +``` + +## `empty` + +#### Signature + +```ts ignore +function empty(it: unknown): it is { + [K in undefined]: never; +}; +``` + +Checks if a given value is an empty object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an empty object, `false` otherwise. + +###### Category + +`Chain` + +#### Examples + +```ts +import { isEmpty } from "@nick/is/empty"; + +isEmpty({}); // true +isEmpty({ a: 1 }); // false +``` + +## `empty` + +#### Signature + +```ts ignore +function empty(it: unknown): it is + | "" + | { + length: 0; + } + | { + [K in undefined]: never; + }; +``` + +Checks if a given value is an empty object, array, or string. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an empty object, array, or string, `false` otherwise. + +###### Category + +`Chain` + +#### Examples + +```ts +import { isEmpty } from "@nick/is/empty"; + +isEmpty({}); // true +isEmpty([]); // true +isEmpty(""); // true + +isEmpty({ a: 1 }); // false +isEmpty([1]); // false +isEmpty("a"); // false +``` + +## `enum` + +#### Signature + +```ts ignore +function enum(it: T | unknowns): it is Enum; +``` + +Check if the given value appears to be a TypeScript `enum` object, which is a +plain object with either all string keys that point to numeric or string values, +or string/numeric keys that point to string/numeric values, which are inversely +mapped to each other (e.g. `A.B === 1 && A[1] === "B"`). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value appears to be a TypeScript `enum` object, `false` otherwise. + +###### Category + +`Objects` + +#### Examples + +```ts +import { isEnum } from "@nick/is/enum"; + +enum Foo { + Bar, // 0 + Baz, // 1 + Qux, // 2 + // implicit reverse mapping: + // 0: "Bar", 1: "Baz", 2: "Qux", +} + +isEnum(Foo); // true + +const obj = { Bar: 0, Baz: 1, Qux: 2 }; +isEnum(obj); // false +``` + +## `enum` + +#### Signature + +```ts ignore +function enum(it: unknown): it is Enum; +``` + +## `enum` + +#### Signature + +```ts ignore +function enum(it: unknown): it is Enum; +``` + +## `error` + +#### Signature + +```ts ignore +function error(it: unknown): it is Error; +``` + +Check if the given value is an instance of the native Error class, or of a +subclass that inherits from it, like `TypeError` or `RangeError`. + +This is more reliable than `instanceof Error`, because it also works across +different realms (e.g. iframes / web workers / browser tabs). It's also more +strict than `instanceof` because it **does not** recognize objects that were +created with `Object.create(Error.prototype)` or `Object.setPrototypeOf` as +being a subclass of `Error`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an error, `false` otherwise. + +###### Category + +`Standard` + +#### Examples + +```ts +import { isError } from "jsr:@nick/is/error"; + +const err = new Error("Something went wrong"); +console.log(isError(err)); // true +console.log(isError(err.message)); // false +``` + +## `even` + +#### Signature + +```ts ignore +function even(it: T): IsEven; +``` + +Checks if a given number / bigint is an even number. Returns `true` if it is +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :----------------------------------------------------------------- | +| **`it`** | The number or bigint to check, either literal or in string format. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `even` + +#### Signature + +```ts ignore +function even(it: number | `${number}`): it is Even; +``` + +Checks if a given number / numeric string is even. Returns `true` if the value +is divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------- | +| **`it`** | The number or numeric string to check. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `even` + +#### Signature + +```ts ignore +function even(it: bigint | `${bigint}`): it is Even; +``` + +Checks if a given bigint or bigint string is an even number. Returns `true` if +the value is divisible by `2`, and `false` otherwise. This usually corresponds +to integers that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------ | +| **`it`** | The bigint or bigint string to check. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `even` + +#### Signature + +```ts ignore +function even(it: unknown): it is Even; +``` + +Checks if a given number / bigint is even. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an even finite integer, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `extendedSetLike` + +#### Signature + +```ts ignore +function extendedSetLike(it: unknown): it is ExtendedSetLike; +``` + +Checks whether the provided value is a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object. The `ExtendedSetLike` interface is the full implementation of a +`ExtendedSetLike` object, including all the composition methods like `union`, +`intersection`, `difference`, and `symmetricDifference`. + +The `ExtendedSetLike` type is the shape of the native `Set` object in JavaScript +**after** the introduction of the TC39 Proposal for Set Methods, which added the +composition methods to the API. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object; otherwise, `false`. + +###### Category + +`Guards` + +## `falsy` + +#### Signature + +```ts ignore +function falsy(it: unknown): it is Falsy; +``` + +Check if the given value is falsy. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is falsy, `false` otherwise. + +#### Examples + +```ts +import { isFalsy } from "@nick/is/falsy"; + +isFalsy(null); // true +isFalsy(undefined); // true +isFalsy(0); // true +isFalsy(""); // true +isFalsy(false); // true +isFalsy([]); // false +``` + +## `finite` + +#### Signature + +```ts ignore +function finite(it: N): it is Finite; +``` + +Checks if a given value is a finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFinite } from "jsr:@nick/is/integer"; + +console.log(isFinite(0)); // true +console.log(isFinite(1)); // true +console.log(isFinite(-1)); // true +console.log(isFinite(1.5)); // true +console.log(isFinite(NaN)); // false +console.log(isFinite(Infinity)); // false +``` + +## `finite` + +#### Signature + +```ts ignore +function finite(it: unknown): it is Finite; +``` + +Checks if a given value is a finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFinite } from "jsr:@nick/is/integer"; + +console.log(isFinite(0)); // true +console.log(isFinite(1)); // true +console.log(isFinite(-1)); // true +console.log(isFinite(1.5)); // true +console.log(isFinite(NaN)); // false +console.log(isFinite(Infinity)); // false +``` + +## `finiteInteger` + +#### Signature + +```ts ignore +function finiteInteger(it: N): it is FiniteInteger; +``` + +Checks if a given value is a finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isFiniteInteger(0)); // true +console.log(isFiniteInteger(1)); // true +console.log(isFiniteInteger(-1)); // true +console.log(isFiniteInteger(1.5)); // false +console.log(isFiniteInteger(NaN)); // false +console.log(isFiniteInteger(Infinity)); // false +``` + +## `finiteInteger` + +#### Signature + +```ts ignore +function finiteInteger(it: unknown): it is FiniteInteger; +``` + +Checks if a given value is a finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isFiniteInteger(0)); // true +console.log(isFiniteInteger(1)); // true +console.log(isFiniteInteger(-1)); // true +console.log(isFiniteInteger(1.5)); // false +console.log(isFiniteInteger(NaN)); // false +console.log(isFiniteInteger(Infinity)); // false +``` + +## `float` + +#### Signature + +```ts ignore +function float(it: N): it is Float; +``` + +Checks if the value is a floating-point number. Supports both single and double +precision floating-point numbers. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a floating-point number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat } from "@nick/is/float"; + +isFloat(1); // false +isFloat(1.0); // false +isFloat(1.1); // true +isFloat(1.00001e1); // true +``` + +## `float` + +#### Signature + +```ts ignore +function float(it: unknown): it is Float; +``` + +Checks if the value is a floating-point number. Supports both single and double +precision floating-point numbers. + +## Rules for what is (and isn't) seen as a floating-point number + +- `0`, `-0` are considered valid floating-point numbers, and return `true`. +- `1`, `-1` and other integers (or _"non-floating"_ values) return `false`. +- Special cases like `Infinity`, `-Infinity`, and `NaN` return `false`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a floating-point number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat } from "@nick/is/float"; + +isFloat(0); // true +isFloat(1); // false +isFloat(1.0); // false +isFloat(1.1); // true +isFloat(1.00001e1); // true +``` + +## `float16` + +#### Signature + +```ts ignore +function float16(it: N): it is Float16; +``` + +Checks if a value is a 16-bit half-precision floating-point number, also known +as `float16` or `binary16`, as defined by the IEEE 754 standard. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a half-precision floating-point number. Otherwise +`false`. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat16 } from "@nick/is/float16"; + +isFloat16(1); // true +isFloat16(1.5); // true +isFloat16(3.140625); // true +isFloat16(NaN); // false +isFloat16(1.1); // false +isFloat16(Math.PI); // false +isFloat16(Infinity); // false +``` + +## `float16` + +#### Signature + +```ts ignore +function float16(it: unknown): it is Float16; +``` + +Checks if a value is a 16-bit half-precision floating-point number, also known +as `float16` or `binary16`, as defined by the IEEE 754 standard. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a half-precision floating-point number. Otherwise +`false`. + +###### Category + +`Numbers` + +## `float16` + +#### Signature + +```ts ignore +function float16(it: any): it is Float16; +``` + +## `float16Array` + +#### Signature + +```ts ignore +function float16Array(it: unknown): it is Float16Array; +``` + +Check if the given value is a `Float16Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Float16Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isFloat16Array } from "jsr:@nick/is/float16array"; + +const arr = new Float16Array(8); +isFloat16Array(arr); // true +isFloat16Array(arr.buffer); // false +``` + +## `float32` + +#### Signature + +```ts ignore +function float32(it: N): it is Float32; +``` + +Checks if the value is a floating-point number. Supports single-precision +floating-point numbers. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a single-precision floating-point number, otherwise +`false`. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat32 } from "@nick/is/float32"; + +isFloat32(1); // false +isFloat32(1.0); // false +isFloat32(1.1); // true +isFloat32(1.00001e1); // true +``` + +## `float32` + +#### Signature + +```ts ignore +function float32(it: unknown): it is Float32; +``` + +Checks if the value is a floating-point number. Supports single-precision +floating-point numbers. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a single-precision floating-point number, otherwise +`false`. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat32 } from "@nick/is/float32"; + +isFloat32(1); // false +isFloat32(1.0); // false +isFloat32(1.1); // true +isFloat32(1.00001e1); // true +``` + +## `float32Array` + +#### Signature + +```ts ignore +function float32Array(it: unknown): it is Float32Array; +``` + +Check if the given value is a `Float32Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Float32Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isFloat32Array } from "jsr:@nick/is/float32array"; + +const arr = new Float32Array(8); +isFloat32Array(arr); // true +isFloat32Array(arr.buffer); // false +``` + +## `float64` + +#### Signature + +```ts ignore +function float64(it: N): it is Float64; +``` + +Checks if the value is a float64-precision floating-point number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a float64-precision floating-point number, `false` +otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat64 } from "jsr:@nick/is/float64"; + +console.log(isFloat64(1.5)); // true +console.log(isFloat64(0)); // false +console.log(isFloat64(1)); // false +console.log(isFloat64(-1)); // false +console.log(isFloat64(NaN)); // false +console.log(isFloat64(Infinity)); // false +``` + +## `float64` + +#### Signature + +```ts ignore +function float64(it: unknown): it is Float64; +``` + +Checks if the value is a float64-precision floating-point number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a float64-precision floating-point number, `false` +otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat64 } from "jsr:@nick/is/float64"; + +console.log(isFloat64(1.5)); // true +console.log(isFloat64(0)); // false +console.log(isFloat64(1)); // false +console.log(isFloat64(-1)); // false +console.log(isFloat64(NaN)); // false +console.log(isFloat64(Infinity)); // false +``` + +## `float64Array` + +#### Signature + +```ts ignore +function float64Array(it: unknown): it is Float64Array; +``` + +Check if the given value is a `Float64Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Float64Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isFloat64Array } from "jsr:@nick/is/float64array"; + +const arr = new Float64Array(8); +isFloat64Array(arr); // true +isFloat64Array(arr.buffer); // false +``` + +## `function` + +#### Signature + +```ts ignore +function function(it: T | unknowns): it is FunctionOrConstructor extends T ? Function : T; +``` + +Check if the given value is a function. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a function, `false` otherwise. + +###### Category + +`Standard` + +#### Examples + +```ts +import { isFunction } from "jsr:@nick/is/function"; + +console.log(isFunction(() => {})); // true +console.log(isFunction(function () {})); // true +console.log(isFunction(class {})); // true +console.log(isFunction(new Function())); // true +console.log(isFunction({})); // false +console.log(isFunction(1)); // false +``` + +## `function` + +#### Signature + +```ts ignore +function function(it: Fn | unknowns): it is Fn; +``` + +## `function` + +#### Signature + +```ts ignore +function function(it: ThisFn | unknowns): it is ThisFn; +``` + +## `function` + +#### Signature + +```ts ignore +function function(it: unknown): it is Function; +``` + +## `function` + +#### Signature + +```ts ignore +function function(it: unknown): it is FunctionOrConstructor; +``` + +## `generator` + +#### Signature + +```ts ignore +function generator( + it: unknown, +): it is Generator; +``` + +Check if the given value is a generator, which is an iterable iterator that was +created with the `function*() { ... }` syntax. + +This is the type of value **_returned_** when a generator function +(`function*() { ... }`) is called, and not the type of the function itself. To +check for the function itself, use `isGeneratorFunction` instead. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a generator, `false` otherwise. + +###### Category + +`Generators` + +#### Examples + +```ts +import { isGenerator } from "jsr:@nick/is/generator"; + +function* gen() { + yield 1; +} +const iter = gen(); + +console.log(isGenerator(iter)); // true +console.log(isGenerator(gen)); // false +``` + +## `generatorFunction` + +#### Signature + +```ts ignore +function generatorFunction(it: unknown): it is GeneratorFunction; +``` + +Checks if a given value is a generator function, which is a function that uses a +distinct syntax and returns a generator object when called. + +To check if a value is a generator object (the actual iterable iterator that is +typically used within `for..of` loops), use +[isGenerator](#isgenerator "Jump to symbol: 'isGenerator'") instead. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a generator function, `false` otherwise. + +###### Category + +`Generators` + +#### Examples + +```ts +import { isGeneratorFunction } from "jsr:@nick/is/generator-function"; + +function* gen() { + yield 1; +} +const iter = gen(); + +console.log(isGeneratorFunction(gen)); // true +console.log(isGeneratorFunction(iter)); // false +``` + +Another example, highlighting the differences between a generator function and a +generator object, using a custom iterable class: + +```ts +import { isGenerator, isGeneratorFunction, isIterable } from "jsr:@nick/is"; + +class Foo { + *delegate() { + return yield* this; // <- thanks to the [Symbol.iterator] method below + } + + *[Symbol.iterator](): IterableIterator { + for (let i = 0; i < 10; i++) yield i; + } +} + +const foo = new Foo(); + +// Since Foo.prototype has a [Symbol.iterator] method, it is iterable: +if (isIterable(foo)) { + // This will log the numbers 1 through 10 + for (const value of foo) console.log(value); +} + +// However, it is _not_ a generator not generator function: +isGenerator(foo); // false +isGeneratorFunction(foo); // false + +// It's delegate and [Symbol.iterator] methods _are_ generator functions: +isGeneratorFunction(foo.delegate); // true +isGeneratorFunction(foo[Symbol.iterator]); // true + +// And they _return_ generator objects...: +const iter1 = foo.delegate(); +const iter2 = foo[Symbol.iterator](); +isGenerator(iter1); // true +isGenerator(iter2); // true + +// ...which are also iterable: +isIterable(iter1); // true +isIterable(iter2); // true +``` + +#### Notes + +This function will **_not_** return `true` for async generator functions, as +they are a distinctly different type of function that returns a different type +of object. Use +[isAsyncGeneratorFunction](#isasyncgeneratorfunction "Jump to symbol: 'isAsyncGeneratorFunction'") +to check for an async generator function instead. + +## `identifier` + +#### Signature + +```ts ignore +function identifier(it: T): it is Identifier; +``` + +Checks if a given string is a valid JavaScript identifier, meaning it can be +used as the name of a variable, function, property, label, or export. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a valid identifier, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isIdentifier } from "jsr:@nick/is/identifier"; + +console.log(isIdentifier("a")); // true +console.log(isIdentifier("1")); // false +console.log(isIdentifier("export")); // false +``` + +## `identifier` + +#### Signature + +```ts ignore +function identifier(it: unknown): it is Identifier; +``` + +Checks if a given value is a valid JavaScript identifier, meaning it can be used +as the name of a variable, function, property, label, or export. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a valid identifier, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isIdentifier } from "jsr:@nick/is/identifier"; + +console.log(isIdentifier("a")); // true +console.log(isIdentifier("1")); // false +console.log(isIdentifier("export")); // false +``` + +## `identifier` + +#### Signature + +```ts ignore +function identifier(it: unknown): it is Identifier; +``` + +Checks if a given value is a valid JavaScript identifier, meaning it can be used +as the name of a variable, function, property, label, or export. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a valid identifier, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isIdentifier } from "jsr:@nick/is/identifier"; + +console.log(isIdentifier("a")); // true +console.log(isIdentifier("1")); // false +console.log(isIdentifier("exportm z=-0fdxz")); // true +``` + +## `infinity` + +#### Signature + +```ts ignore +function infinity(it: unknown): it is Infinity; +``` + +Checks if a given value is a non-finite number (`Infinity` or `-Infinity`). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a non-finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInfinity } from "@nick/is/number/infinity"; + +console.log(isInfinity(Infinity)); // true +console.log(isInfinity(-Infinity)); // true +console.log(isInfinity(1)); // false +console.log(isInfinity(-1)); // false +console.log(isInfinity(NaN)); // false +``` + +## `inRange` + +#### Signature + +```ts ignore +function inRange< + V extends number, + R extends Derange, + Min extends number = R extends [infer M extends number, number, Exclusivity?] + ? M + : R[1] extends Exclusivity ? 0 + : R[0], + Max extends number = R extends [number, infer M extends number, Exclusivity?] + ? M + : R[1] extends Exclusivity ? R[0] + : R[1], + Tex extends Exclusivity = Either< + R extends [number, number, infer T extends Exclusivity] ? T + : R[1] extends Exclusivity ? R[1] + : undefined, + "[)" + >, +>(value: V, ...range: [...R] | Derange): value is InRange; +``` + +Checks if a given number is within a given range. The range can be specified in +multiple ways: + +- As a tuple with the minimum and maximum values, and optional exclusivity + string of either "[]", "(]", "[)", or "()". +- As a tuple with a maximum value and an optional exclusivity string. This + assumes a minimum value of `0`. +- As a single number, which is assumed to be the maximum value, with an assumed + minimum value of `0` and an assumed exclusivity string of "[]". + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------- | +| **`value`** | The number to check. | +| **`range`** | The range to check against. | + +##### Returns + +`true` if the number is within the range, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { inRange } from "jsr:@nick/is/number/in_range"; + +console.log(inRange(1, 0, 2)); // true +console.log(inRange(1, 2, 0)); // false +console.log(inRange(1, 2)); // true +console.log(inRange(1, 2, "(]")); // true +``` + +## `inRange` + +#### Signature + +```ts ignore +function inRange(value: number, ...range: Derange): value is InRange; +``` + +Checks if a given number is within a given range. The range can be specified in +multiple ways: + +- As a tuple with the minimum and maximum values, and optional exclusivity + string of either "[]", "(]", "[)", or "()". +- As a tuple with a maximum value and an optional exclusivity string. This + assumes a minimum value of `0`. +- As a single number, which is assumed to be the maximum value, with an assumed + minimum value of `0` and an assumed exclusivity string of "[]". + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------- | +| **`value`** | The number to check. | +| **`range`** | The range to check against. | + +##### Returns + +`true` if the number is within the range, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { inRange } from "jsr:@nick/is/number/in_range"; + +console.log(inRange(1, 0, 2)); // true +console.log(inRange(1, 2, 0)); // false +console.log(inRange(1, 2)); // true +console.log(inRange(1, 2, "(]")); // true +``` + +## `inRange` + +#### Signature + +```ts ignore +function inRange(value: number, ...range: any[]): undefined; +``` + +## `instance` + +#### Signature + +```ts ignore +function instance(it: unknown, constructor: Constructor): it is T; +``` + +Checks if a given value is an instance of a specific class or constructor. + +This is a type guard function that can be used to determine if a value is an +instance of a class or constructor function, even if the class is not directly +accessible in the current scope. + +##### Parameters + +| Name | Info | +| :---------------- | :-------------------------------------------------- | +| **`it`** | The value to check. | +| **`constructor`** | The class or constructor function to check against. | + +##### Returns + +`true` if it is an instance of the class; otherwise, `false`. + +###### Category + +`Guards` + +## `instance` + +#### Signature + +```ts ignore +function instance>( + it: unknown, + constructor: T, +): it is InstanceType; +``` + +Checks if a given value is an instance of a particular class or constructor. + +##### Parameters + +| Name | Info | +| :---------------- | :-------------------------------------------------- | +| **`it`** | The value to check. | +| **`constructor`** | The class or constructor function to check against. | + +##### Returns + +`true` if it is an instance of the class; otherwise, `false`. + +###### Category + +`Guards` + +## `instance` + +#### Signature + +```ts ignore +function instance, P = InstanceType>( + it: unknown, + constructor: T | Constructor

| P, +): it is InstanceType; +``` + +Checks if a given value is an instance of a specific class or constructor. + +##### Parameters + +| Name | Info | +| :---------------- | :-------------------------------------------------- | +| **`it`** | The value to check. | +| **`constructor`** | The class or constructor function to check against. | + +##### Returns + +`true` if it is an instance of the class; otherwise, `false`. + +###### Category + +`Guards` + +## `instanceof` + +#### Signature + +```ts ignore +function instanceof(it: unknown, constructor: Constructor): it is T; +``` + +Checks if a given value is an instance of a specific class or constructor. + +This is a type guard function that can be used to determine if a value is an +instance of a class or constructor function, even if the class is not directly +accessible in the current scope. + +##### Parameters + +| Name | Info | +| :---------------- | :-------------------------------------------------- | +| **`it`** | The value to check. | +| **`constructor`** | The class or constructor function to check against. | + +##### Returns + +`true` if it is an instance of the class; otherwise, `false`. + +###### Category + +`Guards` + +## `instanceof` + +#### Signature + +```ts ignore +function instanceof>(it: unknown, constructor: T): it is InstanceType; +``` + +Checks if a given value is an instance of a particular class or constructor. + +##### Parameters + +| Name | Info | +| :---------------- | :-------------------------------------------------- | +| **`it`** | The value to check. | +| **`constructor`** | The class or constructor function to check against. | + +##### Returns + +`true` if it is an instance of the class; otherwise, `false`. + +###### Category + +`Guards` + +## `instanceof` + +#### Signature + +```ts ignore +function instanceof, P = InstanceType>(it: unknown, constructor: T | Constructor

| P): it is InstanceType; +``` + +Checks if a given value is an instance of a specific class or constructor. + +##### Parameters + +| Name | Info | +| :---------------- | :-------------------------------------------------- | +| **`it`** | The value to check. | +| **`constructor`** | The class or constructor function to check against. | + +##### Returns + +`true` if it is an instance of the class; otherwise, `false`. + +###### Category + +`Guards` + +## `int16` + +#### Signature + +```ts ignore +function int16(it: unknown): it is Int16; +``` + +Checks if a value is a 16-bit integer (between -32768 and 32767). + +To check for an **unsigned** 16-bit integer (0-65535), use +[isUint16](#isuint16 "Jump to symbol: 'isUint16'"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/number"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -32769; // <- TS2322 Type '-32769' is not assignable to type 'Int16'. +``` + +## `int16` + +#### Signature + +```ts ignore +function int16(it: unknown): it is Int16; +``` + +Checks if a value is a 16-bit integer (between -32768 and 32767). + +To check for an **unsigned** 16-bit integer (0-65535), use +[isUint16](#isuint16 "Jump to symbol: 'isUint16'"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInt16 } from "@nick/is/number"; + +isInt16(32768); // false +isInt16(-32769); // false +isInt16(1); // true +isInt16(32767); // true +isInt16(-32768); // true +``` + +## `int16Array` + +#### Signature + +```ts ignore +function int16Array(it: unknown): it is Int16Array; +``` + +Check if the given value is a `Int16Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Int16Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isInt16Array } from "jsr:@nick/is/int16array"; + +const arr = new Int16Array(8); +isInt16Array(arr); // true +isInt16Array(arr.buffer); // false +``` + +## `int32` + +#### Signature + +```ts ignore +function int32(it: N): it is Int32; +``` + +Checks if a given value is a signed 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a signed 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`int32` `number` + +#### Examples + +```ts +import { type Int32, isInt32, type MaybeInt32 } from "jsr:@type/number/int32"; + +let value = 1 as Int32; + +const setValue = (newValue: MaybeInt32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -2147483649; // <- TS2322 Type '-2147483649' is not assignable to type 'Int32'. +``` + +## `int32` + +#### Signature + +```ts ignore +function int32(it: unknown): it is Int32; +``` + +Checks if a given value is a signed 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a signed 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`int32` `number` + +#### Examples + +```ts +import { isInt32 } from "jsr:@type/number/int32"; + +console.log(isInt32(0x7FFFFFFF)); // <- true +console.log(isInt32(-2147483649)); // <- false +``` + +## `int32Array` + +#### Signature + +```ts ignore +function int32Array(it: unknown): it is Int32Array; +``` + +Check if the given value is a `Int32Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Int32Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isInt32Array } from "jsr:@nick/is/int32array"; + +const arr = new Int32Array(8); +isInt32Array(arr); // true +isInt32Array(arr.buffer); // false +``` + +## `int8` + +#### Signature + +```ts ignore +function int8(it: N): it is Int8; +``` + +Checks if a given value is a signed 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a signed 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInt8 } from "@nick/is/int8"; + +isInt8(1); // true +isInt8(1.0); // false +isInt8(1.1); // false +isInt8(1.00001e1); // false +``` + +## `int8` + +#### Signature + +```ts ignore +function int8(it: unknown): it is Int8; +``` + +Checks if a given value is a signed 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a signed 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInt8 } from "@nick/is/int8"; + +console.log(isInt8(1)); // true +console.log(isInt8(1.0)); // false +console.log(isInt8(1.1)); // false +console.log(isInt8(1.00001e1)); // false +``` + +## `int8Array` + +#### Signature + +```ts ignore +function int8Array(it: unknown): it is Int8Array; +``` + +Check if the given value is a `Int8Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Int8Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isInt8Array } from "jsr:@nick/is/int8array"; + +const arr = new Int8Array(8); +isInt8Array(arr); // true +isInt8Array(arr.buffer); // false +``` + +## `integer` + +#### Signature + +```ts ignore +function integer(it: N): it is Integer; +``` + +Checks if a given value is an integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInteger } from "jsr:@nick/is/integer"; + +console.log(isInteger(0)); // true +console.log(isInteger(1)); // true +console.log(isInteger(-1)); // true +console.log(isInteger(1.5)); // false +console.log(isInteger(NaN)); // false +console.log(isInteger(Infinity)); // false +``` + +## `integer` + +#### Signature + +```ts ignore +function integer(it: unknown): it is Integer; +``` + +Checks if a given value is an integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInteger } from "jsr:@nick/is/integer"; + +console.log(isInteger(0)); // true +console.log(isInteger(1)); // true +console.log(isInteger(-1)); // true +console.log(isInteger(1.5)); // false +console.log(isInteger(NaN)); // false +console.log(isInteger(Infinity)); // false +``` + +## `isWhitespace` + +#### Signature + +```ts ignore +function isWhitespace( + it: S, +): it is IsWhitespace : never>; +``` + +Checks if the provided value is either a string or an iterable of strings that +consists entirely of whitespace characters. + +This function is useful for validating input data, ensuring that it contains +characters other than whitespace. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string or an iterable of strings that consists entirely +of whitespace characters, `false` otherwise. + +###### Category + +`Strings` + +###### Tags + +`whitespace` + +#### Examples + +```ts +import { isWhitespace } from "jsr:@nick/is/whitespace"; + +console.log(isWhitespace(" ")); // true +console.log(isWhitespace("abc")); // false +console.log(isWhitespace(" a ")); // false +console.log(isWhitespace("")); // false +console.log(isWhitespace(" \n\t ")); // true +``` + +## `isWhitespace` + +#### Signature + +```ts ignore +function isWhitespace(it: unknown): it is WhitespaceString; +``` + +## `isWhitespace` + +#### Signature + +```ts ignore +function isWhitespace(it: unknown): it is WhitespaceString; +``` + +## `isWhitespaceChar` + +#### Signature + +```ts ignore +function isWhitespaceChar(it: unknown): it is Whitespace; +``` + +Checks if a given character is a whitespace character. + +This function checks if the provided character is one of the recognized +whitespace characters, including spaces, tabs, newlines, and additional Unicode +whitespace characters. + +##### Parameters + +| Name | Info | +| :------- | :---------------------- | +| **`it`** | The character to check. | + +##### Returns + +`true` if the character is a whitespace character, `false` otherwise. + +###### Category + +`Strings` + +###### Tags + +`whitespace` + +#### Examples + +```ts +import { isWhitespaceChar } from "jsr:@nick/is/whitespace"; + +console.log(isWhitespaceChar(" ")); // true +console.log(isWhitespaceChar("\n")); // true +console.log(isWhitespaceChar("\t")); // true +console.log(isWhitespaceChar("a")); // false +``` + +## `isWhitespaceCode` + +#### Signature + +```ts ignore +function isWhitespaceCode(it: unknown): it is WhitespaceCode; +``` + +Checks if a given value is a whitespace character code. + +This function checks if the provided value is a number and if it is included in +the list of recognized whitespace character codes, which is exposed as the +[`WHITESPACE\_CODES`](#whitespace-codes "Jump to symbol: 'WHITESPACE_CODES'") +array. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a whitespace character code, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike( + it: S, +): it is IsWhitespace; +``` + +Checks if the provided value is either a string or an iterable of strings that +consists entirely of whitespace characters. + +This function is useful for validating input data, ensuring that it contains +characters other than whitespace. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string or an iterable of strings that consists entirely +of whitespace characters, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike( + it: N, +): it is IsWhitespaceCode; +``` + +Checks if the provided value is a whitespace character code. + +This function checks if the provided value is a number and if it is included in +the list of recognized whitespace character codes, which is exposed as the +[`WHITESPACE\_CODES`](#whitespace-codes "Jump to symbol: 'WHITESPACE_CODES'") +array. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a whitespace character code, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike(it: Iterable): it is Iterable; +``` + +Checks if the provided value is either a string or an iterable of strings that +consists entirely of whitespace characters. + +This function is useful for validating input data, ensuring that it contains +characters other than whitespace. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string or an iterable of strings that consists entirely +of whitespace characters, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike(it: number): it is WhitespaceCode; +``` + +Checks if the provided value is a whitespace character code. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a whitespace character code, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike(it: unknown): it is WhitespaceLike; +``` + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike( + it: unknown, +): it is string | WhitespaceCode | Iterable; +``` + +## `iterable` + +#### Signature + +```ts ignore +function iterable(it: unknown): it is Iterable; +``` + +Checks if a given value is an iterable. This includes arrays, strings, maps, +sets, and any other value with a `Symbol.iterator` method. If you need to check +for iterable objects specifically, use `isIterableObject`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an iterable, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isIterable } from "jsr:@nick/is/iterable"; + +console.log(isIterable([1, 2])); // true +console.log(isIterable("foo")); // true +console.log(isIterable(new Map())); // true +console.log(isIterable(new Set())); // true +console.log(isIterable({ [Symbol.iterator]: () => {} })); // true +console.log(isIterable({})); // false +``` + +## `iterableIterator` + +#### Signature + +```ts ignore +function iterableIterator(it: unknown): it is IterableIterator; +``` + +Checks if a given value is an `IterableIterator`, which is an iterator object +that also has a `Symbol.iterator` method that returns a reference to itself. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an `IterableIterator`, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isIterableIterator } from "jsr:@nick/is/iterable-iterator"; + +const iter = [1, 2][Symbol.iterator](); // Array iterator +console.log(isIterableIterator(iter)); // true +console.log(isIterableIterator(iter[Symbol.iterator]())); // true +console.log(isIterableIterator("foo"[Symbol.iterator]())); // false +``` + +## `iterableObject` + +#### Signature + +```ts ignore +function iterableObject(it: unknown): it is IterableObject; +``` + +Checks if a given value is an iterable object. This includes arrays, maps, and +sets, but not strings or other non-object iterables. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an iterable object, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isIterableObject } from "jsr:@nick/is/iterable-object"; + +console.log(isIterableObject([1, 2])); // true +console.log(isIterableObject(new Map())); // true +console.log(isIterableObject(new Set())); // true +console.log(isIterableObject({ [Symbol.iterator]: () => {} })); // true +console.log(isIterableObject("foo")); // false +``` + +## `iterator` + +#### Signature + +```ts ignore +function iterator(it: unknown): it is Iterator; +``` + +Check if the given value is an iterator object. This includes arrays, maps, +sets, and any other value with a `.next` method. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an iterator, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isIterator } from "jsr:@nick/is/iterator"; + +const iterable = [1, 2, 3]; +const iterator = iterable[Symbol.iterator](); +console.log(isIterator(iterator)); // true +console.log(isIterator(iterable)); // false +``` + +## `keyof` + +#### Signature + +```ts ignore +function keyof( + o: T, + k: K, +): k is K & keyof T; +``` + +###### Category + +`Objects` + +#### Examples + +```ts +import { isKeyOf } from "jsr:@nick/is/keyof"; + +const obj = { a: 1, b: 2, c: 3 }; + +console.log(isKeyOf(obj, "a")); // true +console.log(isKeyOf(obj, "b")); // true +console.log(isKeyOf(obj, "c")); // true +console.log(isKeyOf(obj, "d")); // false +``` + +## `keyOf` + +#### Signature + +```ts ignore +function keyOf( + o: T, + k: K, +): k is K & keyof T; +``` + +###### Category + +`Objects` + +#### Examples + +```ts +import { isKeyOf } from "jsr:@nick/is/keyof"; + +const obj = { a: 1, b: 2, c: 3 }; + +console.log(isKeyOf(obj, "a")); // true +console.log(isKeyOf(obj, "b")); // true +console.log(isKeyOf(obj, "c")); // true +console.log(isKeyOf(obj, "d")); // false +``` + +## `map` + +#### Signature + +```ts ignore +function map(it: unknown): it is Map; +``` + +Checks if a given value is a `Map` instance. This is a more reliable check than +`it instanceof Map` because it works across different realms, and it does not +require the `Map` constructor to be the same as the one in the current +environment that the code is running in. + +It also is more strict than `it instanceof Map`, and does not consider any +objects created via `Object.create(Map.prototype)` (or similar constructs) as +valid `Map` instances, while they would pass the `instanceof` check. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Map` instance, `false` otherwise. + +###### Category + +`Keyed Collections` + +#### Examples + +```ts +import { isMap } from "jsr:@nick/is/map"; + +isMap(new Map()); // true +isMap(new WeakMap()); // false +isMap({}); // false +isMap(new Set()); // false +``` + +```ts +import { isMap } from "jsr:@nick/is/map"; + +const fakeMap = Object.create(Map.prototype); +console.log(isMap(fakeMap)); // false +console.log(fakeMap instanceof Map); // true (?!) +``` + +## `mapIterator` + +#### Signature + +```ts ignore +function mapIterator(it: unknown): it is MapIterator; +``` + +Check if the given value is a map iterator, which is an iterable iterator that +yields key-value pairs from a Map object. This is the type of object returned by +the `Map.prototype.entries` and `Map.prototype[Symbol.iterator]` methods. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a map iterator, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isMapIterator } from "jsr:@nick/is/map-iterator"; + +const map = new Map([["foo", 1], ["bar", 2]]); +const iterator = map.entries(); +console.log(isMapIterator(iterator)); // true +console.log(isMapIterator(map)); // false +``` + +## `mapLike` + +#### Signature + +```ts ignore +function mapLike(it: unknown): it is MapLike; +``` + +Checks whether a given value is a +[`MapLike`](#maplike "Jump to symbol: 'MapLike'") object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `MapLike` object; otherwise, `false`. + +## `missing` + +#### Signature + +```ts ignore +function missing(it: unknown): it is null | undefined; +``` + +Check if a given value is missing, which is either `null` or `undefined`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `null` or `undefined`, or `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isMissing } from "jsr:@nick/is/missing"; + +isMissing(null); // true +isMissing(undefined); // true +isMissing(0); // false +isMissing(""); // false +isMissing(false); // false +``` + +## `nan` + +#### Signature + +```ts ignore +function nan(it: N): it is NaN; +``` + +Checks if a given value is `NaN` (not a number). This is a type-safe alias of +the global `isNaN` function, + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `NaN`, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNaN } from "jsr:@type/number"; + +console.log(isNaN(0)); // false +console.log(isNaN(1)); // false +console.log(isNaN(1.5)); // false +console.log(isNaN(NaN)); // true +console.log(isNaN(Infinity)); // false +``` + +## `nan` + +#### Signature + +```ts ignore +function nan(it: unknown): it is NaN; +``` + +Checks if a given value is `NaN` (not a number). This is a type-safe alias of +the global `isNaN` function, + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `NaN`, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNaN } from "jsr:@type/number"; + +console.log(isNaN(0)); // false +console.log(isNaN(1)); // false +console.log(isNaN(1.5)); // false +console.log(isNaN(NaN)); // true +console.log(isNaN(Infinity)); // false +``` + +## `negative` + +#### Signature + +```ts ignore +function negative(it: N): it is Negative; +``` + +Checks if a given value is a negative number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`negative` + +#### Examples + +```ts +import { isNegative } from "jsr:@nick/is/integer"; + +console.log(isNegative(0)); // false +console.log(isNegative(1)); // false +console.log(isNegative(1.5)); // false +console.log(isNegative(NaN)); // false +console.log(isNegative(Infinity)); // false + +console.log(isNegative(-0)); // true +console.log(isNegative(-1)); // true +console.log(isNegative(-Infinity)); // true +``` + +## `negative` + +#### Signature + +```ts ignore +function negative(it: unknown): it is Negative; +``` + +Checks if a given value is a negative number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`negative` + +#### Examples + +```ts +import { isNegative } from "jsr:@nick/is/integer"; + +console.log(isNegative(0)); // false +console.log(isNegative(1)); // false +console.log(isNegative(1.5)); // false +console.log(isNegative(NaN)); // false +console.log(isNegative(Infinity)); // false + +console.log(isNegative(-0)); // true +console.log(isNegative(-1)); // true +console.log(isNegative(-Infinity)); // true +``` + +## `negativeFinite` + +#### Signature + +```ts ignore +function negativeFinite(it: N): it is NegativeFinite; +``` + +Checks if a given value is a negative finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteNumber(0)); // false +console.log(isNegativeFiniteNumber(1)); // false +console.log(isNegativeFiniteNumber(-1)); // true +console.log(isNegativeFiniteNumber(1.5)); // false +console.log(isNegativeFiniteNumber(NaN)); // false +console.log(isNegativeFiniteNumber(Infinity)); // false +``` + +## `negativeFinite` + +#### Signature + +```ts ignore +function negativeFinite(it: unknown): it is NegativeFinite; +``` + +Checks if a given value is a negative finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteNumber(0)); // false +console.log(isNegativeFiniteNumber(1)); // false +console.log(isNegativeFiniteNumber(-1)); // true +console.log(isNegativeFiniteNumber(1.5)); // false +console.log(isNegativeFiniteNumber(NaN)); // false +console.log(isNegativeFiniteNumber(Infinity)); // false +``` + +## `negativeInfinity` + +#### Signature + +```ts ignore +function negativeInfinity(it: unknown): it is NegativeInfinity; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is negative infinity, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `negative` `infinity` + +#### Examples + +```ts +import { isNegativeInfinity } from "@nick/is/number/infinity"; + +console.log(isNegativeInfinity(Infinity)); // false +console.log(isNegativeInfinity(-Infinity)); // true +console.log(isNegativeInfinity(1)); // false +console.log(isNegativeInfinity(-1)); // false +console.log(isNegativeInfinity(NaN)); // false +``` + +## `negativeInteger` + +#### Signature + +```ts ignore +function negativeInteger(it: N): it is NegativeInteger; +``` + +Checks if a given value is a negative integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeInteger(0)); // false +console.log(isNegativeInteger(1)); // false +console.log(isNegativeInteger(-1)); // true +console.log(isNegativeInteger(1.5)); // false +console.log(isNegativeInteger(NaN)); // false +console.log(isNegativeInteger(Infinity)); // false +``` + +## `negativeInteger` + +#### Signature + +```ts ignore +function negativeInteger(it: unknown): it is NegativeInteger; +``` + +Checks if a given value is a negative integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeInteger(0)); // false +console.log(isNegativeInteger(1)); // false +console.log(isNegativeInteger(-1)); // true +console.log(isNegativeInteger(1.5)); // false +console.log(isNegativeInteger(NaN)); // false +console.log(isNegativeInteger(Infinity)); // false +``` + +## `negativeNonZero` + +#### Signature + +```ts ignore +function negativeNonZero(it: N): it is NegativeNonZero; +``` + +Checks if a given value is a negative nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero number, `false` otherwise. + +#### Examples + +```ts +import { isNegativeNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroNumber(0)); // false +console.log(isNegativeNonZeroNumber(1)); // false +console.log(isNegativeNonZeroNumber(-1)); // true +console.log(isNegativeNonZeroNumber(1.5)); // false +console.log(isNegativeNonZeroNumber(NaN)); // false +console.log(isNegativeNonZeroNumber(Infinity)); // false +``` + +## `negativeNonZero` + +#### Signature + +```ts ignore +function negativeNonZero(it: unknown): it is NegativeNonZero; +``` + +Checks if a given value is a negative nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero number, `false` otherwise. + +#### Examples + +```ts +import { isNegativeNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroNumber(0)); // false +console.log(isNegativeNonZeroNumber(1)); // false +console.log(isNegativeNonZeroNumber(-1)); // true +console.log(isNegativeNonZeroNumber(1.5)); // false +console.log(isNegativeNonZeroNumber(NaN)); // false +console.log(isNegativeNonZeroNumber(Infinity)); // false +``` + +## `negativeNonZeroFinite` + +#### Signature + +```ts ignore +function negativeNonZeroFinite( + it: N, +): it is NegativeNonZeroFinite; +``` + +Checks if a given value is a negative nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteNumber(0)); // false +console.log(isNegativeNonZeroFiniteNumber(1)); // false +console.log(isNegativeNonZeroFiniteNumber(-1)); // true +console.log(isNegativeNonZeroFiniteNumber(1.5)); // false +console.log(isNegativeNonZeroFiniteNumber(NaN)); // false +console.log(isNegativeNonZeroFiniteNumber(Infinity)); // false +``` + +## `negativeNonZeroFinite` + +#### Signature + +```ts ignore +function negativeNonZeroFinite(it: unknown): it is NegativeNonZeroFinite; +``` + +Checks if a given value is a negative nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteNumber(0)); // false +console.log(isNegativeNonZeroFiniteNumber(1)); // false +console.log(isNegativeNonZeroFiniteNumber(-1)); // true +console.log(isNegativeNonZeroFiniteNumber(1.5)); // false +console.log(isNegativeNonZeroFiniteNumber(NaN)); // false +console.log(isNegativeNonZeroFiniteNumber(Infinity)); // false +``` + +## `negativeNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function negativeNonZeroFiniteInteger( + it: N, +): it is NegativeNonZeroFiniteInteger; +``` + +Checks if a given value is a negative nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteInteger(0)); // false +console.log(isNegativeNonZeroFiniteInteger(1)); // false +console.log(isNegativeNonZeroFiniteInteger(-1)); // true +console.log(isNegativeNonZeroFiniteInteger(1.5)); // false +console.log(isNegativeNonZeroFiniteInteger(NaN)); // false +console.log(isNegativeNonZeroFiniteInteger(Infinity)); // false +``` + +## `negativeNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function negativeNonZeroFiniteInteger( + it: unknown, +): it is NegativeNonZeroFiniteInteger; +``` + +Checks if a given value is a negative nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteInteger(0)); // false +console.log(isNegativeNonZeroFiniteInteger(1)); // false +console.log(isNegativeNonZeroFiniteInteger(-1)); // true +console.log(isNegativeNonZeroFiniteInteger(1.5)); // false +console.log(isNegativeNonZeroFiniteInteger(NaN)); // false +console.log(isNegativeNonZeroFiniteInteger(Infinity)); // false +``` + +## `negativeNonZeroInteger` + +#### Signature + +```ts ignore +function negativeNonZeroInteger( + it: N, +): it is NegativeNonZeroInteger; +``` + +Checks if a given value is a negative nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroInteger(0)); // false +console.log(isNegativeNonZeroInteger(1)); // false +console.log(isNegativeNonZeroInteger(-1)); // true +console.log(isNegativeNonZeroInteger(1.5)); // false +console.log(isNegativeNonZeroInteger(NaN)); // false +console.log(isNegativeNonZeroInteger(Infinity)); // true +``` + +## `negativeNonZeroInteger` + +#### Signature + +```ts ignore +function negativeNonZeroInteger(it: unknown): it is NegativeNonZeroInteger; +``` + +Checks if a given value is a negative nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroInteger(0)); // false +console.log(isNegativeNonZeroInteger(1)); // false +console.log(isNegativeNonZeroInteger(-1)); // true +console.log(isNegativeNonZeroInteger(1.5)); // false +console.log(isNegativeNonZeroInteger(NaN)); // false +console.log(isNegativeNonZeroInteger(Infinity)); // true +``` + +## `negativeZero` + +#### Signature + +```ts ignore +function negativeZero(it: N): it is NegativeZero; +``` + +Checks if a given value is negative zero, which is a special numeric value in +JavaScript, distinctly different from it's positive counterpart. Checking for +negative zero involves more than simply `x === -0`, as `-0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `-0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is negative zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero } from "jsr:@nick/is/number"; + +console.log(isNegativeZero(-0)); // true +console.log(isNegativeZero(0)); // false +console.log(isNegativeZero(-1)); // false +console.log(isNegativeZero(1)); // false +``` + +## `negativeZero` + +#### Signature + +```ts ignore +function negativeZero(it: unknown): it is NegativeZero; +``` + +Checks if a given value is negative zero, which is a special numeric value in +JavaScript, distinctly different from it's positive counterpart. Checking for +negative zero involves more than simply `x === -0`, as `-0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `-0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is negative zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero } from "jsr:@nick/is/number"; + +console.log(isNegativeZero(-0)); // true +console.log(isNegativeZero(0)); // false +console.log(isNegativeZero(-1)); // false +console.log(isNegativeZero(1)); // false +``` + +## `nonEmptyArray` + +#### Signature + +```ts ignore +function nonEmptyArray( + a: MaybeArray, + test?: Predicate, +): a is NonEmptyArray; +``` + +Checks if the given value is an array with at least one element of a specific +type. + +##### Parameters + +| Name | Info | +| :--------- | :------------------------------------------------------ | +| **`it`** | The value to check. | +| **`test`** | The type guard to check the type of the array elements. | + +##### Returns + +`true` if the value is an array with at least one element of the specific type +(if a `test` predicate is provided), `false` otherwise. + +###### Category + +`Indexed Collections` + +#### Examples + +```ts +import { isNonEmptyArray } from "jsr:@nick/is/array"; + +console.log(isNonEmptyArray([])); // false +console.log(isNonEmptyArray([1, 2, 3])); // true +console.log(isNonEmptyArray({})); // false +``` + +```ts +import { isNonEmptyArray } from "jsr:@nick/is/array"; +import { isString } from "jsr:@nick/is/string"; +import { isNumber } from "jsr:@nick/is/number"; +import { expectType } from "jsr:@nick/is/type/expect"; + +const arr: unknown[] = ["a", "b", "c"]; + +if (isNonEmptyArray(arr, isString)) { + console.log(arr, "is an array of strings"); + // ^? const arr: readonly [string, ...string[]] + expectType(arr); +} else if (isNonEmptyArray(arr, isNumber)) { + console.log(arr, "is an array of numbers"); + // ^? const arr: readonly [number, ...number[]] + expectType(arr); +} else { + console.log(arr, "is not an array of strings or numbers"); + // ^? const arr: readonly unknown[] + expectType(arr); +} +``` + +## `nonEmptyArray` + +#### Signature + +```ts ignore +function nonEmptyArray( + a: unknown, + test?: Predicate, +): a is NonEmptyArray; +``` + +## `nonEmptyArray` + +#### Signature + +```ts ignore +function nonEmptyArray( + a: unknown, + test?: Predicate, +): a is NonEmptyArray; +``` + +## `nonZero` + +#### Signature + +```ts ignore +function nonZero(it: N): it is NonZero; +``` + +Checks if a given value is a nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero } from "jsr:@nick/is/number/nonzero"; + +console.log(isNonZero(1)); // true +console.log(isNonZero(-1)); // true +console.log(isNonZero(1.5)); // true + +console.log(isNonZero(0)); // false +console.log(isNonZero(-0)); // false +console.log(isNonZero(NaN)); // false +console.log(isNonZero(Infinity)); // true +``` + +## `nonZero` + +#### Signature + +```ts ignore +function nonZero(it: unknown): it is NonZero; +``` + +Checks if a given value is a nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero } from "jsr:@nick/is/number/nonzero"; + +console.log(isNonZero(1)); // true +console.log(isNonZero(-1)); // true +console.log(isNonZero(1.5)); // true + +console.log(isNonZero(0)); // false +console.log(isNonZero(-0)); // false +console.log(isNonZero(NaN)); // false +console.log(isNonZero(Infinity)); // true +``` + +## `nonZeroFinite` + +#### Signature + +```ts ignore +function nonZeroFinite(it: N): it is NonZeroFinite; +``` + +Checks if a given value is a nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteNumber(0)); // false +console.log(isNonZeroFiniteNumber(1)); // true +console.log(isNonZeroFiniteNumber(-1)); // true +console.log(isNonZeroFiniteNumber(1.5)); // true +console.log(isNonZeroFiniteNumber(NaN)); // false +console.log(isNonZeroFiniteNumber(Infinity)); // true +``` + +## `nonZeroFinite` + +#### Signature + +```ts ignore +function nonZeroFinite(it: unknown): it is NonZeroFinite; +``` + +Checks if a given value is a nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteNumber(0)); // false +console.log(isNonZeroFiniteNumber(1)); // true +console.log(isNonZeroFiniteNumber(-1)); // true +console.log(isNonZeroFiniteNumber(1.5)); // true +console.log(isNonZeroFiniteNumber(NaN)); // false +console.log(isNonZeroFiniteNumber(Infinity)); // true +``` + +## `nonZeroFiniteInteger` + +#### Signature + +```ts ignore +function nonZeroFiniteInteger(it: N): it is NonZeroFiniteInteger; +``` + +Checks if a given value is a nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteInteger(0)); // false +console.log(isNonZeroFiniteInteger(1)); // true +console.log(isNonZeroFiniteInteger(-1)); // true +console.log(isNonZeroFiniteInteger(1.5)); // false +console.log(isNonZeroFiniteInteger(NaN)); // false +console.log(isNonZeroFiniteInteger(Infinity)); // true +``` + +## `nonZeroFiniteInteger` + +#### Signature + +```ts ignore +function nonZeroFiniteInteger(it: unknown): it is NonZeroFiniteInteger; +``` + +Checks if a given value is a nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteInteger(0)); // false +console.log(isNonZeroFiniteInteger(1)); // true +console.log(isNonZeroFiniteInteger(-1)); // true +console.log(isNonZeroFiniteInteger(1.5)); // false +console.log(isNonZeroFiniteInteger(NaN)); // false +console.log(isNonZeroFiniteInteger(Infinity)); // true +``` + +## `nonZeroInteger` + +#### Signature + +```ts ignore +function nonZeroInteger(it: N): it is NonZeroInteger; +``` + +Checks if a given value is a nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroInteger(0)); // false +console.log(isNonZeroInteger(1)); // true +console.log(isNonZeroInteger(-1)); // true +console.log(isNonZeroInteger(1.5)); // false +console.log(isNonZeroInteger(NaN)); // false +console.log(isNonZeroInteger(Infinity)); // true +``` + +## `nonZeroInteger` + +#### Signature + +```ts ignore +function nonZeroInteger(it: unknown): it is NonZeroInteger; +``` + +Checks if a given value is a nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroInteger(0)); // false +console.log(isNonZeroInteger(1)); // true +console.log(isNonZeroInteger(-1)); // true +console.log(isNonZeroInteger(1.5)); // false +console.log(isNonZeroInteger(NaN)); // false +console.log(isNonZeroInteger(Infinity)); // true +``` + +## `null` + +#### Signature + +```ts ignore +function null(it: unknown): it is null; +``` + +Checks if the value is `null`, and nothing else. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `null`, or `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isNull } from "jsr:@nick/is/null"; + +isNull(null); // true +isNull(undefined); // false +isNull(0); // false +isNull(""); // false +isNull(false); // false +``` + +## `number` + +#### Signature + +```ts ignore +function number(it: unknown): it is number; +``` + +Checks if the given value is a number. This includes all numbers, without +distinguishing between `NaN`, `Infinity`, and other special values. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a number, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isNumber } from "jsr:@nick/is/number"; + +isNumber("123"); // false +isNumber(123); // true +``` + +```ts +import { isNumber } from "jsr:@nick/is/number"; + +const x: unknown = 123; +if (isNumber(x)) { + console.log(x + 1); + // ^? const x: number +} +``` + +## `numberObject` + +#### Signature + +```ts ignore +function numberObject(it: unknown): it is Number; +``` + +Checks if a value is a Number object, which is a boxed-primitive number that was +created either with the `new Number()` syntax, or by wrapping a primitive number +in the `Object()` wrapper function. + +Boxed primitives are strongly discouraged in JavaScript, as they can lead to all +sorts of unexpected behavior and performance issues. As such, this function - +and the other boxed primitive functions like it - are provided for your +convenience, to help you easily ensure your code is not on the receiving end of +such behavior. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a boxed-primitive number object; otherwise, `false`. + +###### Category + +`Boxed Primitives` + +#### Examples + +```ts +import { isNumberObject } from "jsr:@nick/is/number-object"; + +isNumberObject(Object(1)); // true +isNumberObject(new Number(1)); // true + +isNumberObject(Number(1)); // false +isNumberObject(1); // false +``` + +## `object` + +#### Signature + +```ts ignore +function object(it: unknown): it is object; +``` + +Check if the given value is a non-null object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a non-null object, `false` otherwise. + +###### Category + +`Objects` + +#### Examples + +```ts +import { isObject } from "jsr:@nick/is/object"; + +console.log(isObject({})); // true +console.log(isObject(new class {}())); // true +console.log(isObject(new Object())); // true +console.log(isObject([])); // true + +console.log(isObject(() => {})); // false +console.log(isObject(null)); // false +console.log(isObject(undefined)); // false +console.log(isObject(1)); // false +``` + +## `objectLike` + +#### Signature + +```ts ignore +function objectLike(it: unknown): it is object; +``` + +Check if a given value is a non-null object-like value, which includes plain +objects, arrays, functions, classes, class instances, and other objects. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if it is a non-null object-like value, `false` otherwise. + +###### Category + +`Objects` + +#### Examples + +```ts +import { isObjectLike } from "jsr:@nick/is/object-like"; + +console.log(isObjectLike({})); // true +console.log(isObjectLike([])); // true +console.log(isObjectLike(() => {})); // true +console.log(isObjectLike(new class {}())); // true +console.log(isObjectLike(new Object())); // true +console.log(isObjectLike(null)); // false +console.log(isObjectLike(undefined)); // false +console.log(isObjectLike(1)); // false +``` + +## `odd` + +#### Signature + +```ts ignore +function odd(it: T): it is Odd; +``` + +Checks if a given number / bigint is odd. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :----------------------------------------------------------------- | +| **`it`** | The number or bigint to check, either literal or in string format. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `odd` + +#### Signature + +```ts ignore +function odd(it: number | `${number}`): it is Odd; +``` + +Checks if a given number / numeric string is odd. Returns `true` if the value is +not divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------- | +| **`it`** | The number or numeric string to check. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `odd` + +#### Signature + +```ts ignore +function odd(it: bigint | `${bigint}`): it is Odd; +``` + +Checks if a given bigint or bigint string is an odd number. Returns `true` if +the value is not divisible by `2`, and `false` otherwise. This usually +corresponds to integers that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------ | +| **`it`** | The bigint or bigint string to check. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `odd` + +#### Signature + +```ts ignore +function odd(it: unknown): it is Odd; +``` + +Checks if a given number / bigint is odd. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an odd finite integer, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `plainObject` + +#### Signature + +```ts ignore +function plainObject>(it: unknown): it is T; +``` + +Check if the given value is a plain object, which is an object that either has a +prototype of `null` or `Object.prototype`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a plain object, `false` otherwise. + +###### Category + +`Objects` + +#### Examples + +```ts +import { isPlainObject } from "jsr:@nick/is/plain-object"; + +console.log(isPlainObject({})); // true +console.log(isPlainObject(new class {}())); // true +console.log(isPlainObject(new Object())); // true + +console.log(isPlainObject([])); // false +console.log(isPlainObject(() => {})); // false +console.log(isPlainObject(null)); // false +console.log(isPlainObject(undefined)); // false +console.log(isPlainObject(1)); // false +``` + +## `positive` + +#### Signature + +```ts ignore +function positive(it: N): it is Positive; +``` + +Checks if a given value is a positive number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive } from "jsr:@nick/is/integer"; + +console.log(isPositive(0)); // true +console.log(isPositive(1)); // true +console.log(isPositive(-1)); // false +console.log(isPositive(1.5)); // true +console.log(isPositive(NaN)); // false +console.log(isPositive(Infinity)); // true +``` + +## `positive` + +#### Signature + +```ts ignore +function positive(it: unknown): it is Positive; +``` + +Checks if a given value is a positive number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive } from "jsr:@nick/is/integer"; + +console.log(isPositive(0)); // true +console.log(isPositive(1)); // true +console.log(isPositive(-1)); // false +console.log(isPositive(1.5)); // true +console.log(isPositive(NaN)); // false +console.log(isPositive(Infinity)); // true +``` + +## `positiveFinite` + +#### Signature + +```ts ignore +function positiveFinite(it: N): it is PositiveFinite; +``` + +Checks if a given value is a positive finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteNumber(0)); // false +console.log(isPositiveFiniteNumber(1)); // true +console.log(isPositiveFiniteNumber(-1)); // false +console.log(isPositiveFiniteNumber(1.5)); // true +console.log(isPositiveFiniteNumber(NaN)); // false +console.log(isPositiveFiniteNumber(Infinity)); // false +``` + +## `positiveFinite` + +#### Signature + +```ts ignore +function positiveFinite(it: unknown): it is PositiveFinite; +``` + +Checks if a given value is a positive finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteNumber(0)); // false +console.log(isPositiveFiniteNumber(1)); // true +console.log(isPositiveFiniteNumber(-1)); // false +console.log(isPositiveFiniteNumber(1.5)); // true +console.log(isPositiveFiniteNumber(NaN)); // false +console.log(isPositiveFiniteNumber(Infinity)); // false +``` + +## `positiveInfinity` + +#### Signature + +```ts ignore +function positiveInfinity(it: unknown): it is PositiveInfinity; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is positive infinity, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `positive` `infinity` + +#### Examples + +```ts +import { isPositiveInfinity } from "@nick/is/number/infinity"; + +console.log(isPositiveInfinity(Infinity)); // false +console.log(isPositiveInfinity(-Infinity)); // true +console.log(isPositiveInfinity(1)); // false +console.log(isPositiveInfinity(-1)); // false +console.log(isPositiveInfinity(NaN)); // false +``` + +## `positiveInteger` + +#### Signature + +```ts ignore +function positiveInteger(it: N): it is PositiveInteger; +``` + +Checks if a given value is a positive integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveInteger(0)); // true +console.log(isPositiveInteger(1)); // true +console.log(isPositiveInteger(-1)); // false +console.log(isPositiveInteger(1.5)); // false +console.log(isPositiveInteger(NaN)); // false +console.log(isPositiveInteger(Infinity)); // false +``` + +## `positiveInteger` + +#### Signature + +```ts ignore +function positiveInteger(it: unknown): it is PositiveInteger; +``` + +Checks if a given value is a positive integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveInteger(0)); // true +console.log(isPositiveInteger(1)); // true +console.log(isPositiveInteger(-1)); // false +console.log(isPositiveInteger(1.5)); // false +console.log(isPositiveInteger(NaN)); // false +console.log(isPositiveInteger(Infinity)); // false +``` + +## `positiveNonZero` + +#### Signature + +```ts ignore +function positiveNonZero(it: N): it is PositiveNonZero; +``` + +Checks if a given value is a positive nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroNumber(0)); // false +console.log(isPositiveNonZeroNumber(1)); // true +console.log(isPositiveNonZeroNumber(-1)); // false +console.log(isPositiveNonZeroNumber(1.5)); // true +console.log(isPositiveNonZeroNumber(NaN)); // false +console.log(isPositiveNonZeroNumber(Infinity)); // true +``` + +## `positiveNonZero` + +#### Signature + +```ts ignore +function positiveNonZero(it: unknown): it is PositiveNonZero; +``` + +Checks if a given value is a positive nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroNumber(0)); // false +console.log(isPositiveNonZeroNumber(1)); // true +console.log(isPositiveNonZeroNumber(-1)); // false +console.log(isPositiveNonZeroNumber(1.5)); // true +console.log(isPositiveNonZeroNumber(NaN)); // false +console.log(isPositiveNonZeroNumber(Infinity)); // true +``` + +## `positiveNonZero` + +#### Signature + +```ts ignore +function positiveNonZero(it: unknown): it is PositiveNonZero; +``` + +## `positiveNonZeroFinite` + +#### Signature + +```ts ignore +function positiveNonZeroFinite( + it: N, +): it is PositiveNonZeroFinite; +``` + +Checks if a given value is a positive nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteNumber(0)); // false +console.log(isPositiveNonZeroFiniteNumber(1)); // true +console.log(isPositiveNonZeroFiniteNumber(-1)); // false +console.log(isPositiveNonZeroFiniteNumber(1.5)); // true +console.log(isPositiveNonZeroFiniteNumber(NaN)); // false +console.log(isPositiveNonZeroFiniteNumber(Infinity)); // true +``` + +## `positiveNonZeroFinite` + +#### Signature + +```ts ignore +function positiveNonZeroFinite(it: unknown): it is PositiveNonZeroFinite; +``` + +Checks if a given value is a positive nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteNumber(0)); // false +console.log(isPositiveNonZeroFiniteNumber(1)); // true +console.log(isPositiveNonZeroFiniteNumber(-1)); // false +console.log(isPositiveNonZeroFiniteNumber(1.5)); // true +console.log(isPositiveNonZeroFiniteNumber(NaN)); // false +console.log(isPositiveNonZeroFiniteNumber(Infinity)); // true +``` + +## `positiveNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function positiveNonZeroFiniteInteger( + it: N, +): it is PositiveNonZeroFiniteInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteInteger(0)); // false +console.log(isPositiveNonZeroFiniteInteger(1)); // true +console.log(isPositiveNonZeroFiniteInteger(-1)); // false +console.log(isPositiveNonZeroFiniteInteger(1.5)); // false +console.log(isPositiveNonZeroFiniteInteger(NaN)); // false +console.log(isPositiveNonZeroFiniteInteger(Infinity)); // true +``` + +## `positiveNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function positiveNonZeroFiniteInteger( + it: unknown, +): it is PositiveNonZeroFiniteInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteInteger(0)); // false +console.log(isPositiveNonZeroFiniteInteger(1)); // true +console.log(isPositiveNonZeroFiniteInteger(-1)); // false +console.log(isPositiveNonZeroFiniteInteger(1.5)); // false +console.log(isPositiveNonZeroFiniteInteger(NaN)); // false +console.log(isPositiveNonZeroFiniteInteger(Infinity)); // true +``` + +## `positiveNonZeroInteger` + +#### Signature + +```ts ignore +function positiveNonZeroInteger( + it: N, +): it is PositiveNonZeroInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroInteger(0)); // false +console.log(isPositiveNonZeroInteger(1)); // true +console.log(isPositiveNonZeroInteger(-1)); // false +console.log(isPositiveNonZeroInteger(1.5)); // false +console.log(isPositiveNonZeroInteger(NaN)); // false +console.log(isPositiveNonZeroInteger(Infinity)); // true +``` + +## `positiveNonZeroInteger` + +#### Signature + +```ts ignore +function positiveNonZeroInteger(it: unknown): it is PositiveNonZeroInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroInteger(0)); // false +console.log(isPositiveNonZeroInteger(1)); // true +console.log(isPositiveNonZeroInteger(-1)); // false +console.log(isPositiveNonZeroInteger(1.5)); // false +console.log(isPositiveNonZeroInteger(NaN)); // false +console.log(isPositiveNonZeroInteger(Infinity)); // true +``` + +## `positiveZero` + +#### Signature + +```ts ignore +function positiveZero(it: N): it is PositiveZero; +``` + +Checks if a given value is positive zero, which is a special numeric value in +JavaScript, distinctly different from it's negative counterpart. Checking for +positive zero involves more than simply `x === +0`, as `+0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `+0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is positive zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero } from "jsr:@nick/is/number"; + +console.log(isPositiveZero(-0)); // false +console.log(isPositiveZero(0)); // true +console.log(isPositiveZero(-1)); // false +console.log(isPositiveZero(1)); // false +``` + +## `positiveZero` + +#### Signature + +```ts ignore +function positiveZero(it: unknown): it is PositiveZero; +``` + +Checks if a given value is positive zero, which is a special numeric value in +JavaScript, distinctly different from it's negative counterpart. Checking for +positive zero involves more than simply `x === +0`, as `+0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `+0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is positive zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero } from "jsr:@nick/is/number"; + +console.log(isPositiveZero(-0)); // false +console.log(isPositiveZero(0)); // true +console.log(isPositiveZero(-1)); // false +console.log(isPositiveZero(1)); // false +``` + +## `present` + +#### Signature + +```ts ignore +function present(it: T | null | undefined): it is NonNullable; +``` + +Check if the given value is not `null` or `undefined`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is not null or undefined, or `false` otherwise. + +###### Category + +`Primitives` + +###### See Also + +- [isMissing](#ismissing "Jump to symbol: 'isMissing'") for the opposite of this + function. + +#### Examples + +```ts +import { isPresent } from "jsr:@nick/is/present"; + +isPresent(null); // false +isPresent(undefined); // false +isPresent(0); // true +isPresent(""); // true +isPresent(false); // true +``` + +## `primitive` + +#### Signature + +```ts ignore +function primitive(it: unknown): it is Primitive; +``` + +Checks if a given value is a primitive string, number, bigint, boolean, symbol, +null, or undefined. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a primitive, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isPrimitive } from "jsr:@nick/is/primitive"; + +isPrimitive("foo"); // true +isPrimitive(42); // true +isPrimitive(BigInt(42)); // true +isPrimitive(true); // true +isPrimitive(Symbol("foo")); // true +isPrimitive(null); // true +isPrimitive(undefined); // true + +isPrimitive({}); // false +isPrimitive(new String("foo")); // false +isPrimitive(new Number(42)); // false +isPrimitive(new Boolean(true)); // false +``` + +## `printable` + +#### Signature + +```ts ignore +function printable(x: unknown): x is Printable; +``` + +Check if a value is printable, meaning it is either a `string`, `number`, +`bigint`, `boolean`, `null` or `undefined`. This is useful for logging and +debugging purposes. The complentary type +[`Printable`](#printable "Jump to symbol: 'Printable'") can be used on the +type-level to represent values that are usable within a template literal type +syntax. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is printable, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isPrintable } from "jsr:@nick/is/printable"; + +console.log(isPrintable("hello")); // true +console.log(isPrintable(1)); // true +console.log(isPrintable(BigInt(1))); // true +console.log(isPrintable(true)); // true +console.log(isPrintable(null)); // true +console.log(isPrintable(undefined)); // true +console.log(isPrintable({})); // false +console.log(isPrintable(Symbol())); // false +``` + +## `promise` + +#### Signature + +```ts ignore +function promise(it: unknown): it is Promise; +``` + +Checks if a given value is a native `Promise` instance. This is a more reliable +alternative to `it instanceof Promise` because it also works across different +realms (e.g., iframes, workers, etc.). + +Note: This guard does not consider custom promise-like objects with `.then` +methods to be promises. If your use case requires that, use `isPromiseLike`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Promise`, `false` otherwise. + +###### Category + +`Async/Await` + +#### Examples + +```ts +import { isPromise } from "jsr:@nick/is/promise"; + +console.log(isPromise(Promise.resolve())); // true +console.log(isPromise({ then: () => {} })); // false +console.log(isPromise({})); // false +``` + +## `promiseLike` + +#### Signature + +```ts ignore +function promiseLike(it: unknown): it is PromiseLike; +``` + +Check if the given value is a `PromiseLike` type, which includes both native +`Promise` instances and custom promise-like objects with a `.then` method +(sometimes referred to as "thenables"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `PromiseLike`, `false` otherwise. + +###### Category + +`Async/Await` + +#### Examples + +```ts +import { isPromiseLike } from "jsr:@nick/is/promise-like"; + +console.log(isPromiseLike(Promise.resolve())); // true +console.log(isPromiseLike({ then: () => {} })); // true +console.log(isPromiseLike({})); // false +``` + +## `propertyKey` + +#### Signature + +```ts ignore +function propertyKey(value: unknown): value is PropertyKey; +``` + +Checks if the given value is of the `PropertyKey` type (i.e. string, number, or +symbol). + +In JavaScript, a property key can technically only be a string or a symbol, and +all other values are coerced to strings. TypeScript includes numbers in its +definition of this type, and therefore so does this function. But it is worth +noting that even though a number _can_ be used to indexed access an array-like +object, the number is coerced to a string behind the scenes. + +##### Parameters + +| Name | Info | +| :---------- | :------------------ | +| **`value`** | The value to check. | + +##### Returns + +`true` if the value is a property key, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isPropertyKey } from "jsr:@nick/is/property-key"; + +isPropertyKey("foo"); // true +isPropertyKey(42); // true +isPropertyKey(Symbol("foo")); // true +isPropertyKey({ foo: "bar" }); // false +``` + +## `readableStream` + +#### Signature + +```ts ignore +function readableStream(it: unknown): it is ReadableStream; +``` + +Checks if [it](#it "Jump to symbol: 'it'") is a `ReadableStream` object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `ReadableStream`, `false` otherwise. + +###### Category + +`Streams` + +#### Examples + +```ts +import { isReadableStream } from "jsr:@nick/is/readable-stream"; + +const stream = new ReadableStream(); +isReadableStream(stream); // true + +const stream2 = new TransformStream(); +isReadableStream(stream2); // false + +const stream3 = new WritableStream(); +isReadableStream(stream3); // false +``` + +## `reader` + +#### Signature + +```ts ignore +function reader(it: unknown): it is Reader; +``` + +Checks if a given value is an asynchronous reader, which is an object that +implements the `read` method as per Deno's `Reader` interface. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an asynchronous Reader, `false` otherwise. + +###### Category + +`I/O` + +#### Examples + +```ts +import { isReader } from "jsr:@nick/is/reader"; + +const file = await Deno.open("file.txt"); +isReader(file); // true + +const socket = new WebSocket("ws://example.com"); +isReader(socket); // false +``` + +## `readerSync` + +#### Signature + +```ts ignore +function readerSync(it: unknown): it is ReaderSync; +``` + +Checks if a given value is a synchronous reader, which is an object that +implements the `readSync` method as per Deno's `ReaderSync` interface. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a synchronous Reader, `false` otherwise. + +###### Category + +`I/O` + +#### Examples + +```ts +import { isReaderSync } from "jsr:@nick/is/reader-sync"; + +const file = Deno.openSync("file.txt"); +isReaderSync(file); // true + +const socket = new WebSocket("ws://example.com"); +isReaderSync(socket); // false +``` + +## `readonlyCollection` + +#### Signature + +```ts ignore +function readonlyCollection(it: unknown): it is ReadonlyCollection; +``` + +Checks whether the provided value is a +[`ReadonlyCollection`](#readonlycollection "Jump to symbol: 'ReadonlyCollection'") +object. The `ReadonlyCollection` interface is the minimum requirement for a +value to be used in the composition methods found in `ExtendedSetLike` +implementations, such as `union`, `intersection`, `difference`, and +`symmetricDifference`. + +This type is the **bare minimal** requirement for a value to be considered a +"set-like" object in JavaScript, and only requires the `has`, `keys`, and `size` +members to be present. As such, native `Set` objects and also native `Map` +objects both qualify as `ReadonlyCollection` objects. For a more specific check, +see [`isSetLike`](#issetlike "Jump to symbol: 'isSetLike'") or +[`isExtendedSetLike`](#isextendedsetlike "Jump to symbol: 'isExtendedSetLike'"), +which check for the full API of a Set object, with or without the composition +methods added by the TC39 proposal, respectively. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a +[`ReadonlyCollection`](#readonlycollection "Jump to symbol: 'ReadonlyCollection'") +object; otherwise, `false`. + +###### Category + +`Guards` + +## `readonlySetLike` + +#### Signature + +```ts ignore +function readonlySetLike(it: unknown): it is ReadonlyCollection; +``` + +Checks whether the provided value is a +[`ReadonlyCollection`](#readonlycollection "Jump to symbol: 'ReadonlyCollection'") +object. The `ReadonlyCollection` interface is the minimum requirement for a +value to be used in the composition methods found in `ExtendedSetLike` +implementations, such as `union`, `intersection`, `difference`, and +`symmetricDifference`. + +This type is the **bare minimal** requirement for a value to be considered a +"set-like" object in JavaScript, and only requires the `has`, `keys`, and `size` +members to be present. As such, native `Set` objects and also native `Map` +objects both qualify as `ReadonlyCollection` objects. For a more specific check, +see [`isSetLike`](#issetlike "Jump to symbol: 'isSetLike'") or +[`isExtendedSetLike`](#isextendedsetlike "Jump to symbol: 'isExtendedSetLike'"), +which check for the full API of a Set object, with or without the composition +methods added by the TC39 proposal, respectively. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a +[`ReadonlyCollection`](#readonlycollection "Jump to symbol: 'ReadonlyCollection'") +object; otherwise, `false`. + +###### Category + +`Guards` + +## `regexp` + +#### Signature + +```ts ignore +function regexp(it: unknown): it is RegExp; +``` + +Check if the given value is a regular expression, which is an object that +represents a pattern of text that can be used to perform pattern matching with +strings. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a regular expression, `false` otherwise. + +###### Category + +`Standard` + +#### Examples + +```ts +import { isRegExp } from "jsr:@nick/is/regexp"; + +const regex = /foo/; +console.log(isRegExp(regex)); // true +console.log(isRegExp("foo")); // false +``` + +## `regExp` + +#### Signature + +```ts ignore +function regExp(it: unknown): it is RegExp; +``` + +Check if the given value is a regular expression, which is an object that +represents a pattern of text that can be used to perform pattern matching with +strings. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a regular expression, `false` otherwise. + +###### Category + +`Standard` + +#### Examples + +```ts +import { isRegExp } from "jsr:@nick/is/regexp"; + +const regex = /foo/; +console.log(isRegExp(regex)); // true +console.log(isRegExp("foo")); // false +``` + +## `registeredSymbol` + +#### Signature + +```ts ignore +function registeredSymbol(it: unknown): it is RegisteredSymbol; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a registered symbol, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isRegisteredSymbol } from "jsr:@nick/is/registered-symbol"; + +isRegisteredSymbol(Symbol.for("foo")); // true + +isRegisteredSymbol(Symbol("foo")); // false +isRegisteredSymbol(Symbol.iterator); // false +isRegisteredSymbol("@@foo"); // false +``` + +```ts +import { + isRegisteredSymbol, + type RegisteredSymbol, +} from "jsr:@nick/is/registered-symbol"; + +function doSomething(key: RegisteredSymbol): void { + if (isRegisteredSymbol(key)) { + // ... do something ... + } +} + +const key = Symbol.for("foo"); +doSomething(key); +``` + +```ts +import { + isRegisteredSymbol, + RegisteredSymbol, +} from "jsr:@nick/is/registered-symbol"; + +function assertRegisteredSymbol( + value: unknown, +): asserts value is RegisteredSymbol { + if (!isRegisteredSymbol(value)) { + throw new Error("Expected a registered symbol."); + } +} +``` + +## `semver` + +#### Signature + +```ts ignore +function semver(it: unknown): it is SemVer; +``` + +Check if the given value is a valid semantic version string, according to the +Semantic Versioning 2.0.0 specification as per https://semver.org. This function +does not check if the version is a valid version range, but simply validates it +against the regular expression pattern from the specification. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if it is a valid semantic version string, `false` otherwise. + +###### Category + +`Strings` + +#### Examples + +```ts +import { isSemVer } from "jsr:@nick/is/semver"; + +console.log(isSemVer("1.2.3")); // true +console.log(isSemVer("1.2.3-alpha")); // true +console.log(isSemVer("1.2.3+build")); // true +console.log(isSemVer("1.2.3-alpha+build")); // true +console.log(isSemVer("1.2.3-alpha.1")); // true +console.log(isSemVer("1.2")); // false +``` + +## `set` + +#### Signature + +```ts ignore +function set(it: unknown): it is Set; +``` + +Checks if a given value is a `Set` instance. This is a more reliable check than +`it instanceof Set` because it also works across different realms. + +It's also more strict than `instanceof` operations, only recognizing an object +as a `Set` instance if it was created with a valid construct operation of either +the `Set` constructor or a subclass of it. As such, +`Object.create(Set.prototype)` and similar avenues will return `false`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Set` instance, `false` otherwise. + +###### Category + +`Keyed Collections` + +#### Examples + +```ts +import { isSet } from "jsr:@nick/is/set"; + +isSet(new Set()); // true +isSet(new WeakSet()); // false +isSet(new Map()); // false +isSet([]); // false +isSet(Object.create(Set.prototype)); // false +``` + +## `setIterator` + +#### Signature + +```ts ignore +function setIterator(it: unknown): it is SetIterator; +``` + +Check if the given value is a set iterator, which is an iterable iterator that +yields key-value pairs from a Set object. This is the type of object returned by +the `Set.prototype.entries` and `Set.prototype[Symbol.iterator]` methods. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a set iterator, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isSetIterator } from "jsr:@nick/is/set-iterator"; + +const set = new Set(["foo", "bar", "foo"]); +const iter = set[Symbol.iterator](); +console.log(isSetIterator(iterator)); // true +console.log(isSetIterator(set)); // false +``` + +## `setLike` + +#### Signature + +```ts ignore +function setLike(it: unknown): it is SetLike; +``` + +Checks whether the provided value is a +[`SetLike`](#setlike "Jump to symbol: 'SetLike'") object. The `SetLike` +interface is the base implementation of a `ExtendedSetLike` object, without any +additional composition methods like `union` or `intersection`. + +This type is the shape of the native `Set` object in JavaScript **prior** to the +introduction of the TC39 Proposal for Set Methods, which added the composition +methods to the API. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a [`SetLike`](#setlike "Jump to symbol: 'SetLike'") +object; otherwise, `false`. + +###### Category + +`Guards` + +## `sharedArrayBuffer` + +#### Signature + +```ts ignore +function sharedArrayBuffer(it: unknown): it is SharedArrayBuffer; +``` + +Returns `true` if [`it`](#it "Jump to symbol: 'it'") is a `SharedArrayBuffer`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `SharedArrayBuffer`, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isSharedArrayBuffer } from "jsr:@nick/is/shared-array-buffer"; + +const buffer = new ArrayBuffer(8); +const shared = new SharedArrayBuffer(8); + +isSharedArrayBuffer(buffer); // false +isSharedArrayBuffer(shared); // true +``` + +## `string` + +#### Signature + +```ts ignore +function string(it: unknown): it is string; +``` + +Checks if the given value is a string. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isString } from "jsr:@nick/is/string"; + +const x: unknown = "hello"; +if (isString(x)) { + console.log(x.toUpperCase()); + // ^? const x: string +} +``` + +## `stringIterator` + +#### Signature + +```ts ignore +function stringIterator( + it: unknown, +): it is StringIterator; +``` + +Check if the given value is a string iterator, which is an iterable iterator +that yields individual characters from a string literal or String object. This +is the type of object returned by `String.prototype[Symbol.iterator]`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string iterator, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isStringIterator } from "jsr:@nick/is/string-iterator"; + +const str = "foo"; +const iter = str[Symbol.iterator](); +console.log(isStringIterator(iterator)); // true +console.log(isStringIterator(str)); // false +``` + +## `stringObject` + +#### Signature + +```ts ignore +function stringObject(it: unknown): it is String; +``` + +Checks if a value is a string object, which is a boxed-primitive string that was +created via the `new String()` constructor, or by wrapping a primitive string in +the `Object()` wrapper function. + +Boxed primitives are strongly discouraged in JavaScript, as they can lead to all +sorts of unexpected behavior and performance issues. As such, this function - +and the other boxed primitive functions like it - are provided for your +convenience, to help you easily ensure your code is not on the receiving end of +such behavior. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string object; otherwise, `false`. + +###### Category + +`Boxed Primitives` + +#### Examples + +```ts +import { isStringObject } from "jsr:@nick/is/string-object"; + +isStringObject(new String("abc")); // true +isStringObject(Object("abc")); // true + +isStringObject("abc"); // false +isStringObject("abc" as unknown); // false +``` + +## `symbol` + +#### Signature + +```ts ignore +function symbol(it: unknown): it is symbol; +``` + +Check if the given value is a symbol. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a symbol, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isSymbol } from "jsr:@nick/is/symbol"; + +isSymbol(Symbol("foo")); // true +isSymbol(Symbol.iterator); // true +isSymbol(Symbol.for("foo")); // true +isSymbol("@@foo"); // false +``` + +## `symbolObject` + +#### Signature + +```ts ignore +function symbolObject(it: unknown): it is Symbol; +``` + +Checks if a value is a symbol object, which is a boxed-primitive symbol that was +created by wrapping a primitive symbol in the `Object()` wrapper function. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a boxed-primitive symbol object; otherwise, `false`. + +###### Category + +`Boxed Primitives` + +#### Examples + +```ts +import { isSymbolObject } from "jsr:@nick/is/symbol-object"; + +isSymbolObject(Object(Symbol("abc"))); // true + +isSymbolObject(Symbol("abc")); // false +isSymbolObject(Symbol.iterator); // false +isSymbolObject(Symbol.for("abc")); // false +isSymbolObject("@@abc"); // false +``` + +## `tagged` + +#### Signature + +```ts ignore +function tagged(it: O): it is O & { + readonly [Symbol.toStringTag]: NormalizeTag; +}; +``` + +Checks if a given value has a `Symbol.toStringTag` property, and optionally +checks if the value of that property matches the given +[tag](#tag "Jump to symbol: 'tag'"). + +##### Parameters + +| Name | Info | +| :-------- | :-------------------------- | +| **`it`** | The value to check. | +| **`tag`** | The value to check against. | + +##### Returns + +`true` if the value has a `Symbol.toStringTag` property that matches the given +[tag](#tag "Jump to symbol: 'tag'") (if provided), otherwise `false`. + +###### Category + +`Objects` + +## `templateObject` + +#### Signature + +```ts ignore +function templateObject(it: unknown): it is TemplateObject; +``` + +Checks if the given value is a template strings object, which is an object with +a `raw` property that is an array of strings. + +This type fulfills the requirements of the `String.raw` method without +necessarily being an array of strings, as well. Useful for validating template +literal call sites in tagged template functions, which often times are called +with just a plain object with a `raw` property. + +For a more strict check see +[`isTemplateStringsArray`](#istemplatestringsarray "Jump to symbol: 'isTemplateStringsArray'"), +which checks if the value is _also_ an array of strings. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a template strings object, `false` otherwise. + +###### Category + +`Template Literals` + +#### Examples + +```ts +import { + isTemplateObject, +} from "jsr:@nick/is/template-object"; + +console.log( + isTemplateObject({ raw: ["a", "b", "c"] }) +); // true + +// Additional properties are allowed: +console.log( + isTemplateObject({ raw: ["a", "b", "c"], other: 1 }) +); // true + +// Mimicking a template strings array will pass: +console.log( + isTemplateObject(Object.assign(["\1"], { raw: ["\\1"] }) +); // true + +// However, just having any old `raw` property is not enough: +console.log( + isTemplateObject({ raw: 1 }) +); // false +``` + +## `templateStringsArray` + +#### Signature + +```ts ignore +function templateStringsArray(it: unknown): it is TemplateStringsArray; +``` + +Checks if the given value is a template strings array, which is an array of +strings with an own property named `raw` that also is an array of strings. This +is the type of array provided to tagged template literals for the first +argument, and is represented as the type `TemplateStringsArray` in TypeScript. + +This predicate's type is a supertype of the one checked by its more lenient +counterpart, +[`isTemplateObject`](#istemplateobject "Jump to symbol: 'isTemplateObject'"), +which only checks if the value is an object with a `raw` property that is an +array of strings. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a TemplateStringsArray, `false` otherwise. + +###### Category + +`Template Literals` + +#### Examples + +```ts +import { isTemplateStringsArray } from "jsr:@nick/is/template-strings-array"; + +console.log(isTemplateStringsArray(["a", "b", "c"])); // false +console.log(isTemplateStringsArray({ raw: ["a", "b", "c"] })); // false + +function print(strings: TemplateStringsArray, ...values: any[]): string; +function print(...vals: unknown[]): string; +function print(...vals: unknown[]): string { + const [strings, ...values] = vals; + if (isTemplateStringsArray(strings)) { + return String.raw(strings, ...values); + } else { + return JSON.stringify(vals); + } +} + +print(["a", "b", "c"], 1, 2, 3); // '[["a", "b", "c"], 1, 2, 3]' +print`a${1}b${2}c${3}`; // a1b2c3 +``` + +## `truthy` + +#### Signature + +```ts ignore +function truthy(it: U): it is Exclude; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is truthy, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isTruthy } from "jsr:@nick/is/truthy"; + +isTruthy(1); // true +isTruthy("foo"); // true +isTruthy(true); // true +isTruthy({}); // true + +isTruthy(0); // false +isTruthy(""); // false +isTruthy(false); // false +isTruthy(null); // false +isTruthy(undefined); // false +``` + +## `typedArray` + +#### Signature + +```ts ignore +function typedArray( + it: TypedArray | unknowns, +): it is TypedArray; +``` + +Checks if a given value is a typed array, which is a view over a raw binary data +buffer (e.g. `ArrayBuffer`) that provides a fixed-size, typed view into the +buffer. If the [type](#type "Jump to symbol: 'type'") parameter is given, it +checks if the value is that specific typed array type (e.g. `"Uint8Array"` -> +`Uint8Array`). + +For a value to pass this check, it must be an instance of the intrinsic +`%TypedArray%` constructor, and have the `%TypedArrayPrototype%` prototype +inherited by all native typed array types: + +- `Uint8Array` +- `Uint8ClampedArray` +- `Uint16Array` +- `Uint32Array` +- `Int8Array` +- `Int16Array` +- `Int32Array` +- `Float16Array` +- `Float32Array` +- `Float64Array` +- `BigInt64Array` +- `BigUint64Array` + +To check for a specific typed array type, use the `type` parameter or one of the +type-specific checks like `isUint8Array`, etc. + +##### Parameters + +| Name | Info | +| :--------- | :----------------------------------------------------------- | +| **`it`** | The value to check. | +| **`type`** | Name of a specific typed array type to check for (optional). | + +##### Returns + +`true` if the value is a typed array, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isTypedArray } from "jsr:@nick/is/typed-array"; + +const arr = new Uint8Array(8); +isTypedArray(arr); // true +isTypedArray(arr, "Uint8Array"); // true +``` + +## `typedArray` + +#### Signature + +```ts ignore +function typedArray( + it: unknown, +): it is TypedArray; +``` + +Checks if a given value is a typed array, which is a view over a raw binary data +buffer (e.g. `ArrayBuffer`) that provides a fixed-size, typed view into the +buffer. If the [type](#type "Jump to symbol: 'type'") parameter is given, it +checks if the value is that specific typed array type (e.g. `"Uint8Array"` -> +`Uint8Array`). + +For a value to pass this check, it must be an instance of the intrinsic +`%TypedArray%` constructor, and have the `%TypedArrayPrototype%` prototype +inherited by all native typed array types: + +- `Uint8Array` +- `Uint8ClampedArray` +- `Uint16Array` +- `Uint32Array` +- `Int8Array` +- `Int16Array` +- `Int32Array` +- `Float16Array` +- `Float32Array` +- `Float64Array` +- `BigInt64Array` +- `BigUint64Array` + +To check for a specific typed array type, use the `type` parameter or one of the +type-specific checks like `isUint8Array`, etc. + +##### Parameters + +| Name | Info | +| :--------- | :----------------------------------------------------------- | +| **`it`** | The value to check. | +| **`type`** | Name of a specific typed array type to check for (optional). | + +##### Returns + +`true` if the value is a typed array, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isTypedArray } from "jsr:@nick/is/typed-array"; + +const arr = new Uint8Array(8); +isTypedArray(arr); // true +isTypedArray(arr, "Uint8Array"); // true +``` + +## `typedArray` + +#### Signature + +```ts ignore +function typedArray( + it: TypedArray | unknowns, + type: K, +): it is TypedArrayTypeMap[K]; +``` + +Checks if a given value is a typed array of a specific +[type](#type "Jump to symbol: 'type'"). The +[type](#type "Jump to symbol: 'type'") parameter must be one of the following +strings: + +- `"Uint8Array"` +- `"Uint8ClampedArray"` +- `"Uint16Array"` +- `"Uint32Array"` +- `"Int8Array"` +- `"Int16Array"` +- `"Int32Array"` +- `"Float16Array"` +- `"Float32Array"` +- `"Float64Array"` +- `"BigInt64Array"` +- `"BigUint64Array"` + +##### Parameters + +| Name | Info | +| :--------- | :------------------------------------------------ | +| **`it`** | The value to check. | +| **`type`** | Name of a specific typed array type to check for. | + +##### Returns + +`true` if the value is a typed array of the specified type, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isTypedArray } from "jsr:@nick/is/typed-array"; + +const arr = new Uint8Array(8); +isTypedArray(arr, "Uint8Array"); // true +isTypedArray(arr, "Uint16Array"); // false +``` + +## `typedArray` + +#### Signature + +```ts ignore +function typedArray( + it: unknown, + type: K, +): it is TypedArrayTypeMap[K]; +``` + +Checks if a given value is a typed array of a specific +[type](#type "Jump to symbol: 'type'"). The +[type](#type "Jump to symbol: 'type'") parameter must be one of the following +strings: + +- `"Uint8Array"` +- `"Uint8ClampedArray"` +- `"Uint16Array"` +- `"Uint32Array"` +- `"Int8Array"` +- `"Int16Array"` +- `"Int32Array"` +- `"Float16Array"` +- `"Float32Array"` +- `"Float64Array"` +- `"BigInt64Array"` +- `"BigUint64Array"` + +##### Parameters + +| Name | Info | +| :--------- | :------------------------------------------------ | +| **`it`** | The value to check. | +| **`type`** | Name of a specific typed array type to check for. | + +##### Returns + +`true` if the value is a typed array of the specified type, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isTypedArray } from "jsr:@nick/is/typed-array"; + +const arr = new Uint8Array(8); +isTypedArray(arr, "Uint8Array"); // true +isTypedArray(arr, "Uint16Array"); // false +``` + +## `typedArray` + +#### Signature + +```ts ignore +function typedArray(it: unknown, type?: string): it is TypedArray; +``` + +Checks if a given value is a typed array. + +##### Parameters + +| Name | Info | +| :--------- | :----------------------------------------------------------- | +| **`it`** | The value to check. | +| **`type`** | Name of a specific typed array type to check for (optional). | + +##### Returns + +`true` if the value is a typed array, `false` otherwise. + +###### Category + +`Binary Data Structures` + +## `uint16` + +#### Signature + +```ts ignore +function uint16(it: N): it is Uint16; +``` + +Checks if a given value is an unsigned 16-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `uint16` + +#### Signature + +```ts ignore +function uint16(it: unknown): it is Uint16; +``` + +Checks if a given value is an unsigned 16-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `uint16Array` + +#### Signature + +```ts ignore +function uint16Array(it: unknown): it is Uint16Array; +``` + +Check if the given value is a `Uint16Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Uint16Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isUint16Array } from "jsr:@nick/is/uint16array"; + +const arr = new Uint16Array(8); +isUint16Array(arr); // true +isUint16Array(arr.buffer); // false +``` + +## `uint32` + +#### Signature + +```ts ignore +function uint32(it: N): it is Uint32; +``` + +Checks if a given value is an unsigned 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `uint32` + +#### Signature + +```ts ignore +function uint32(it: unknown): it is Uint32; +``` + +Checks if a given value is an unsigned 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `uint32Array` + +#### Signature + +```ts ignore +function uint32Array(it: unknown): it is Uint32Array; +``` + +Check if the given value is a `Uint32Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Uint32Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isUint32Array } from "jsr:@nick/is/uint32array"; + +const arr = new Uint32Array(8); +isUint32Array(arr); // true +isUint32Array(arr.buffer); // false +``` + +## `uint8` + +#### Signature + +```ts ignore +function uint8(it: N): it is Uint8; +``` + +Checks if a given value is an unsigned 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint8 } from "jsr:@nick/is/uint8"; + +isUint8(1); // true +isUint8(128); // true +isUint8(0xFF); // true +isUint8(-1); // false +isUint8(420); // false +``` + +## `uint8` + +#### Signature + +```ts ignore +function uint8(it: unknown): it is Uint8; +``` + +Checks if a given value is an unsigned 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint8 } from "jsr:@nick/is/uint8"; + +isUint8(1); // true +isUint8(128); // true +isUint8(0xFF); // true +isUint8(-1); // false +isUint8(420); // false +``` + +## `uint8Array` + +#### Signature + +```ts ignore +function uint8Array(it: unknown): it is Uint8Array; +``` + +Check if the given value is a `Uint8Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Uint8Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isUint8Array } from "jsr:@nick/is/uint8array"; + +const arr = new Uint8Array(8); +isUint8Array(arr); // true +isUint8Array(arr.buffer); // false +``` + +## `uint8ClampedArray` + +#### Signature + +```ts ignore +function uint8ClampedArray(it: unknown): it is Uint8ClampedArray; +``` + +Check if the given value is a `Uint8ClampedArray` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Uint8ClampedArray` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isUint8ClampedArray } from "jsr:@nick/is/uint8clampedarray"; + +const arr = new Uint8ClampedArray(8); +isUint8ClampedArray(arr); // true +isUint8ClampedArray(arr.buffer); // false +``` + +## `undefined` + +#### Signature + +```ts ignore +function undefined(it: unknown): it is undefined; +``` + +Checks if the value is `undefined`, and nothing else. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `undefined`, or `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isUndefined } from "jsr:@nick/is/undefined"; + +isUndefined(null); // false +isUndefined(undefined); // true +isUndefined(0); // false +isUndefined(void 0); // true +isUndefined(""); // false +``` + +```ts +import { isUndefined } from "jsr:@nick/is/undefined"; + +let value: number | undefined; +if (isUndefined(value)) { + value; + // ^? let value: undefined + value = 0; + // ^? let value: number | undefined +} else { + value += 1; + // ^? let value: number +} +``` + +## `uniqueSymbol` + +#### Signature + +```ts ignore +function uniqueSymbol(it: unknown): it is UniqueSymbol; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a unique symbol, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isUniqueSymbol } from "jsr:@nick/is/unique-symbol"; + +isUniqueSymbol(Symbol("foo")); // true +isUniqueSymbol(Symbol.iterator); // false +isUniqueSymbol(Symbol.for("foo")); // false +``` + +## `url` + +#### Signature + +```ts ignore +function url(it: unknown): it is URL; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a URL object, `false` otherwise. + +###### Category + +`Web APIs` + +#### Examples + +```ts +import { isURL } from "jsr:@nick/is/url"; + +console.log(isURL(new URL("https://example.com"))); // true +console.log(isURL(new URL("https://example.com").toString())); // false +console.log(isURL({ href: "https://example.com" })); // false +console.log(isURL({ ...new URL("https://example.com") })); // false +``` + +## `urlSearchParams` + +#### Signature + +```ts ignore +function urlSearchParams(it: unknown): it is URLSearchParams; +``` + +Checks if a value is a URLSearchParams object. + +This function is useful for checking if a value is an instance of the native +`URLSearchParams` class, without leaning on the `instanceof` operator (which +known to be unreliable in certain environments and across different realms). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a URLSearchParams object, `false` otherwise. + +###### Category + +`Web APIs` + +#### Examples + +```ts +import { isURLSearchParams } from "jsr:@nick/is/url-search-params"; + +console.log(isURLSearchParams(new URLSearchParams())); // true +console.log(isURLSearchParams(new URLSearchParams("a=1&b=2"))); // true +console.log(isURLSearchParams(new URL("https://foobar.com?a=1").searchParams)); // true +console.log(isURLSearchParams({})); // false +console.log(isURLSearchParams(new URL("data:"))); // false +``` + +## `urlString` + +#### Signature + +```ts ignore +function urlString(it: unknown): it is URLString; +``` + +Checks if a value is a string that is a valid, parsable URL capable of being +passed to the `URL` constructor. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a URL string, `false` otherwise. + +###### Category + +`Web APIs` + +#### Examples + +```ts +import { isURLString } from "jsr:@nick/is/url-string"; + +console.log(isURLString("https://example.com")); // true +console.log(isURLString("data:")); // true +console.log(isURLString("https://foo")); // false +console.log(isURLString("example.com")); // false +``` + +## `weakKey` + +#### Signature + +```ts ignore +function weakKey(it: unknown): it is WeakKey; +``` + +Checks if a value is valid as a weak key, meaning it can be used as a key in a +`WeakMap`, a value in a `WeakSet`, or as the target of a `WeakRef`. Weak keys +can also be used as the "unregister token" argument in both the `register` and +`unregister` methods of the `FinalizationRegistry` API. + +This always includes non-null objects, arrays, and functions. Since ES2023+ it +also includes symbols that are not globally registered via `Symbol.for`. + +##### Parameters + +| Name | Info | +| :------- | :------------------- | +| **`it`** | The value you check. | + +##### Returns + +`true` if it is a valid WeakKey, otherwise `false`. + +###### Category + +`Weak Collections` + +###### See Also + +- https://mdn.io/WeakMap for more information on `WeakMap` and weak keys. + +#### Examples + +```ts +import { isWeakKey } from "jsr:@nick/is/weak-key"; + +// objects and functions are always valid weak keys: +console.log(isWeakKey({})); // true +console.log(isWeakKey(() => {})); // true + +// starting in ES2023+, symbols are also valid weak keys: +console.log(isWeakKey(Symbol("a"))); // true +console.log(isWeakKey(Symbol.iterator)); // true + +// however, globally registered symbols are not: +console.log(isWeakKey(Symbol.for("a"))); // false + +// primitives are never valid weak keys: +console.log(isWeakKey(1)); // false +console.log(isWeakKey("a")); // false +``` + +## `weakMap` + +#### Signature + +```ts ignore +function weakMap( + it: WeakMap | null | undefined, +): it is WeakMap; +``` + +Checks if [`it`](#it "Jump to symbol: 'it'") is a `WeakMap` object. For more +information on this language feature, refer to the +[MDN Documentation](https://mdn.io/WeakMap). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +true if it is a `WeakMap`, otherwise false. + +###### Category + +`Weak Collections` + +###### Tags + +`WeakMap` + +#### Examples + +```ts +import { isWeakMap } from "jsr:@nick/is/weak-map"; + +const strong = new Map([[{ a: 1 }, 1], [{ b: 2 }, 2]]); +const weak1 = new WeakMap([[{ a: 1 }, 1], [{ b: 2 }, 2]]); +const weak2 = new WeakSet([{ a: 1 }, { b: 2 }]); + +isWeakMap(strong); // false +isWeakMap(weak1); // true +isWeakMap(weak2); // false +``` + +## `weakMap` + +#### Signature + +```ts ignore +function weakMap(it: unknown): it is WeakMap; +``` + +Checks if [`obj`](#obj "Jump to symbol: 'obj'") is a `WeakMap` object. For more +information on this language feature, see the +[MDN Reference](https://mdn.io/WeakMap). + +##### Parameters + +| Name | Info | +| :-------- | :------------------ | +| **`obj`** | The value to check. | + +##### Returns + +true if it is a `WeakMap`, otherwise false. + +###### Category + +`Weak Collections` + +###### Tags + +`WeakMap` + +## `weakMap` + +#### Signature + +```ts ignore +function weakMap( + obj: unknown, +): obj is WeakMap; +``` + +## `weakRef` + +#### Signature + +```ts ignore +function weakRef( + obj: WeakRef | null | undefined, +): obj is WeakRef; +``` + +Checks if [`obj`](#obj "Jump to symbol: 'obj'") is a WeakRef. For more +information on this type of object, refer to the +[MDN Documentation](https://mdn.io/WeakRef). + +##### Parameters + +| Name | Info | +| :-------- | :------------------ | +| **`obj`** | The value to check. | + +##### Returns + +true if it is a `WeakRef`, otherwise false. + +###### Category + +`Weak Collections` + +#### Examples + +```ts +import { isWeakRef } from "jsr:@nick/is/weak-ref"; + +const strong = { a: 1 }; +const weak1 = new WeakRef(strong); +const weak2 = new WeakMap([[{ a: 1 }, 1], [{ b: 2 }, 2]]); + +console.log(isWeakRef(strong)); // false +console.log(isWeakRef(weak1)); // true +console.log(isWeakRef(weak2)); // false +``` + +## `weakRef` + +#### Signature + +```ts ignore +function weakRef(obj: unknown): obj is WeakRef; +``` + +Checks if [`obj`](#obj "Jump to symbol: 'obj'") is a WeakRef. For more +information on this type of object, refer to the +[MDN Documentation](https://mdn.io/WeakRef). + +##### Parameters + +| Name | Info | +| :-------- | :------------------ | +| **`obj`** | The value to check. | + +##### Returns + +true if it is a `WeakRef`, otherwise false. + +## `weakRef` + +#### Signature + +```ts ignore +function weakRef(obj: unknown): obj is WeakRef; +``` + +## `weakSet` + +#### Signature + +```ts ignore +function weakSet( + it: WeakSet | null | undefined, +): it is WeakSet; +``` + +Checks if [`it`](#it "Jump to symbol: 'it'") is a `WeakSet` object. For more +information on this language feature, refer to the +[MDN Documentation](https://mdn.io/WeakSet). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +true if it is a `WeakSet`, otherwise false. + +###### Category + +`Weak Collections` + +###### Tags + +`WeakSet` + +#### Examples + +```ts +import { isWeakSet } from "jsr:@nick/is/weak-set"; + +const strong = new Set([1, 2]); +const weak1 = new WeakSet([{ a: 1 }, { b: 2 }]); +const weak2 = new WeakMap([[{ a: 1 }, 1], [{ b: 2 }, 2]]); + +console.log(isWeakSet(strong)); // false +console.log(isWeakSet(weak1)); // true +console.log(isWeakSet(weak2)); // false +``` + +## `weakSet` + +#### Signature + +```ts ignore +function weakSet(it: unknown): it is WeakSet; +``` + +Checks if [`obj`](#obj "Jump to symbol: 'obj'") is a `WeakSet` object. For more +information on this language feature, see the +[MDN Reference](https://mdn.io/WeakSet). + +##### Parameters + +| Name | Info | +| :-------- | :------------------ | +| **`obj`** | The value to check. | + +##### Returns + +true if it is a `WeakSet`, otherwise false. + +###### Category + +`Weak Collections` + +###### Tags + +`WeakSet` + +## `weakSet` + +#### Signature + +```ts ignore +function weakSet(obj: unknown): obj is WeakSet; +``` + +## `wellKnownSymbol` + +#### Signature + +```ts ignore +function wellKnownSymbol(it: unknown): it is WellKnownSymbol; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a well-known symbol, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isWellKnownSymbol } from "jsr:@nick/is/well-known-symbol"; + +isWellKnownSymbol(Symbol.iterator); // true +isWellKnownSymbol(Symbol.asyncIterator); // true +isWellKnownSymbol(Symbol.hasInstance); // true + +isWellKnownSymbol(Symbol.for("Symbol.iterator")); // false +isWellKnownSymbol(Symbol("Symbol.iterator")); // false +``` + +## `whitespace` + +#### Signature + +```ts ignore +function whitespace( + it: S, +): it is IsWhitespace : never>; +``` + +Checks if the provided value is either a string or an iterable of strings that +consists entirely of whitespace characters. + +This function is useful for validating input data, ensuring that it contains +characters other than whitespace. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string or an iterable of strings that consists entirely +of whitespace characters, `false` otherwise. + +###### Category + +`Strings` + +###### Tags + +`whitespace` + +#### Examples + +```ts +import { isWhitespace } from "jsr:@nick/is/whitespace"; + +console.log(isWhitespace(" ")); // true +console.log(isWhitespace("abc")); // false +console.log(isWhitespace(" a ")); // false +console.log(isWhitespace("")); // false +console.log(isWhitespace(" \n\t ")); // true +``` + +## `whitespace` + +#### Signature + +```ts ignore +function whitespace(it: unknown): it is WhitespaceString; +``` + +## `whitespace` + +#### Signature + +```ts ignore +function whitespace(it: unknown): it is WhitespaceString; +``` + +## `whitespaceChar` + +#### Signature + +```ts ignore +function whitespaceChar(it: unknown): it is Whitespace; +``` + +Checks if a given character is a whitespace character. + +This function checks if the provided character is one of the recognized +whitespace characters, including spaces, tabs, newlines, and additional Unicode +whitespace characters. + +##### Parameters + +| Name | Info | +| :------- | :---------------------- | +| **`it`** | The character to check. | + +##### Returns + +`true` if the character is a whitespace character, `false` otherwise. + +###### Category + +`Strings` + +###### Tags + +`whitespace` + +#### Examples + +```ts +import { isWhitespaceChar } from "jsr:@nick/is/whitespace"; + +console.log(isWhitespaceChar(" ")); // true +console.log(isWhitespaceChar("\n")); // true +console.log(isWhitespaceChar("\t")); // true +console.log(isWhitespaceChar("a")); // false +``` + +## `whitespaceCode` + +#### Signature + +```ts ignore +function whitespaceCode(it: unknown): it is WhitespaceCode; +``` + +Checks if a given value is a whitespace character code. + +This function checks if the provided value is a number and if it is included in +the list of recognized whitespace character codes, which is exposed as the +[`WHITESPACE\_CODES`](#whitespace-codes "Jump to symbol: 'WHITESPACE_CODES'") +array. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a whitespace character code, `false` otherwise. + +## `whitespaceLike` + +#### Signature + +```ts ignore +function whitespaceLike( + it: S, +): it is IsWhitespace; +``` + +Checks if the provided value is either a string or an iterable of strings that +consists entirely of whitespace characters. + +This function is useful for validating input data, ensuring that it contains +characters other than whitespace. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string or an iterable of strings that consists entirely +of whitespace characters, `false` otherwise. + +## `whitespaceLike` + +#### Signature + +```ts ignore +function whitespaceLike( + it: N, +): it is IsWhitespaceCode; +``` + +Checks if the provided value is a whitespace character code. + +This function checks if the provided value is a number and if it is included in +the list of recognized whitespace character codes, which is exposed as the +[`WHITESPACE\_CODES`](#whitespace-codes "Jump to symbol: 'WHITESPACE_CODES'") +array. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a whitespace character code, `false` otherwise. + +## `whitespaceLike` + +#### Signature + +```ts ignore +function whitespaceLike(it: Iterable): it is Iterable; +``` + +Checks if the provided value is either a string or an iterable of strings that +consists entirely of whitespace characters. + +This function is useful for validating input data, ensuring that it contains +characters other than whitespace. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string or an iterable of strings that consists entirely +of whitespace characters, `false` otherwise. + +## `whitespaceLike` + +#### Signature + +```ts ignore +function whitespaceLike(it: number): it is WhitespaceCode; +``` + +Checks if the provided value is a whitespace character code. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a whitespace character code, `false` otherwise. + +## `whitespaceLike` + +#### Signature + +```ts ignore +function whitespaceLike(it: unknown): it is WhitespaceLike; +``` + +## `whitespaceLike` + +#### Signature + +```ts ignore +function whitespaceLike( + it: unknown, +): it is string | WhitespaceCode | Iterable; +``` + +## `writableStream` + +#### Signature + +```ts ignore +function writableStream(it: unknown): it is WritableStream; +``` + +Checks if [it](#it "Jump to symbol: 'it'") is a `WritableStream` object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `WritableStream`, `false` otherwise. + +###### Category + +`Streams` + +#### Examples + +```ts +import { isWritableStream } from "jsr:@nick/is/writable-stream"; +a; +const stream = new WritableStream(); +isWritableStream(stream); // true + +const stream2 = new TransformStream(); +isWritableStream(stream2); // false + +const stream3 = new ReadableStream(); +isWritableStream(stream3); // false +``` + +## `writer` + +#### Signature + +```ts ignore +function writer(it: unknown): it is Writer; +``` + +Checks if a given value is an asynchronous Writer, which is an object that +implements a `write` method as per Deno's `Writer` interface. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an asynchronous Writer, `false` otherwise. + +###### Category + +`I/O` + +#### Examples + +```ts +import { isWriter } from "jsr:@nick/is/writer"; + +isWriter(Deno.stdout); // true +isWriter(Deno.stderr); // true +isWriter(Deno.stdin); // false +``` + +## `writerSync` + +#### Signature + +```ts ignore +function writerSync(it: unknown): it is WriterSync; +``` + +Checks if a given value is a synchronous writer, which is an object that +implements a `writeSync` method as per Deno's `WriterSync` interface. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a synchronous writer, `false` otherwise. + +###### Category + +`I/O` + +#### Examples + +```ts +import { isWriterSync } from "jsr:@nick/is/writer-sync"; + +const file = Deno.openSync("file.txt", { write: true }); +isWriterSync(file); // true + +const socket = new WebSocket("ws://example.com"); +isWriterSync(socket); // false +``` + +## `zero` + +#### Signature + +```ts ignore +function zero(it: N): it is Zero; +``` + +Checks if a given value is a zero number. This includes both positive and +negative zero. It also supports numbers and numeric strings. + +- To check exclusively for `-0`, use + [isNegativeZero](#isnegativezero "Jump to symbol: 'isNegativeZero'") instead. +- To check exclusively for `+0` (meaning zero, but **not** negative zero), use + [isPositiveZero](#ispositivezero "Jump to symbol: 'isPositiveZero'") instead. + +###### Category + +`Numbers` + +## `zero` + +#### Signature + +```ts ignore +function zero(it: unknown): it is Zero; +``` + +Checks if a given value is a zero number. This includes both positive and +negative zero. It also supports numbers and numeric strings. + +- To check exclusively for `-0`, use + [isNegativeZero](#isnegativezero "Jump to symbol: 'isNegativeZero'") instead. +- To check exclusively for `+0` (meaning zero, but **not** negative zero), use + [isPositiveZero](#ispositivezero "Jump to symbol: 'isPositiveZero'") instead. + +###### Category + +`Numbers` + +## `ArrayBufferLike` + +#### Signature + +```ts ignore +export type ArrayBufferLike = ArrayBuffer | SharedArrayBuffer; +``` + +Represents an "ArrayBuffer-like" value, which is either an `ArrayBuffer` or +`SharedArrayBuffer` instance. + +###### Category + +`Binary Data Structures` + +## `ArrayLikeObject` + +#### Signature + +```ts ignore +export type ArrayLikeObject = ArrayLike & object; +``` + +Represents an object that has a `length` property that is a finite unsigned +integer, and where the object is not a function. This is the type that the +function +[`isArrayLikeObject`](#isarraylikeobject "Jump to symbol: 'isArrayLikeObject'") +narrows its inputs to. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +###### Category + +`Indexed Collections` + +## `AsyncIterableObject` + +#### Signature + +```ts ignore +export type AsyncIterableObject = AsyncIterable & object; +``` + +An object that implements the `AsyncIterable` interface. This is the type that +the +[isAsyncIterableObject](#isasynciterableobject "Jump to symbol: 'isAsyncIterableObject'") +function checks for and (narrows to). + +##### Type Parameters + +- **`T`** + +--- + +###### Category + +`Iterables` + +## `BigInteger` + +#### Signature + +```ts ignore +export type BigInteger = CastInt; +``` + +Casts a value into a big integer type (which is really just a bigint). If the +value is not a bigint or a string containing a valid integer, it will resolve to +`never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `Cast` + +#### Signature + +```ts ignore +export type Cast = Extract & T; +``` + +Casts a value into a specific numeric type. If the value is not a number, it +will resolve to `never`, indicating its incompatibility with the type. + +This is a low-level utility type that primarily serves as an internal helper for +more user-friendly types like [Integer](#integer "Jump to symbol: 'Integer'") +and [Positive](#positive "Jump to symbol: 'Positive'"). Unless you're building +custom numeric types with your own branding, you most likely never directly +handle this type in the wild. + +##### Type Parameters + +- **`N`** +- **`T`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { Cast } from "jsr:@nick/is/number"; + +declare const MY_DOUBLE: unique symbol; +type DOUBLE = Cast; + +let x = 4.3210123210 as DOUBLE; +let y = 3.1415926535 as DOUBLE; + +console.log(x + y); // 7.4626049745 + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'DOUBLE'. +``` + +## `CastInt` + +#### Signature + +```ts ignore +export type CastInt = Extract & T; +``` + +Casts a value into a specific integer type. If the value is not a bigint, it +will resolve to `never`, indicating its incompatibility with the type. + +This is a low-level utility type that primarily serves as an internal helper for +more user-friendly types like +[BigInteger](#biginteger "Jump to symbol: 'BigInteger'") or +[PositiveBigInteger](#positivebiginteger "Jump to symbol: 'PositiveBigInteger'"). +Unless you're building custom numeric types with your own branding, you most +likely will never directly handle this type in the wild. + +##### Type Parameters + +- **`N`** +- **`T`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { CastInt } from "jsr:@nick/is/number"; + +declare const INTEGER: unique symbol; +type INTEGER = CastInt; + +let x = 3n as INTEGER; +let y = 5n as INTEGER; + +console.log(x + y); // 8n +``` + +## `DateString` + +#### Signature + +```ts ignore +export type DateString = string & IsDateString; +``` + +Represents a valid date string that can be parsed by the native `Date` +constructor without any additional formatting or help from external tools. + +This is a branded nominal type that can be used to strictly distinguish between +regular strings and those that have been validated as date strings through a +runtime check like +[`isDateString`](#isdatestring "Jump to symbol: 'isDateString'"). + +Combined with the aforementioned type guard, this type allows you to enforce the +validity of date strings both at runtime and compile time. If your users are not +exposed to this type alias, the only way a value of this type can be created is +by satisfying the `isDateString` function check. + +###### Category + +`Types` + +###### Tags + +`date-string` `nominal` + +## `Enum` + +#### Signature + +```ts ignore +export type Enum = EnumLike & T; +``` + +Represents a TypeScript `enum` object, which is defined as a plain object that +satisfies one of the following conditions: + +- String or numeric keys mapped to string or numeric values. +- Values can be constant or computed. + +> Declared keys may only be literal static strings. Numeric keys are not allowed +> in the declaration of an enum. The only legal way to create an enum with +> numeric keys like `"0"` is for the compiler to generate them. + +String-to-string enums **may not** have reverse mappings. It is only supported +for constant numeric values (whether explicitly specified via initializers, or +implicitly assigned by the TS compiler). + +> When defined with the `enum` keyword and constant numeric values (or no +> explicit values specified at all, which defaults to `0` for the first key and +> increments by `1` for each subsequent key), the TypeScript compiler +> auto-generates an implicit reverse-mapping from the values back to their +> respective keys. + +##### Type Parameters + +- **`T`** extends `EnumLike` (default: `EnumLike`) + +--- + +#### Examples + +Constant enum definition + +```ts +enum Abc { + B = 0, + C = 1, +} +``` + +Mixed-value enum definition (no reverse mapping) + +```ts +// Mixing string and numeric values in an enum definition will +// prevent the compiler from generating reverse mappings (since +// it only generates such mappings for constant numeric values). +enum Abc { + B = 0, + C = "c", +} +``` + +Constant enum definition (implicit value assignment) + +```ts +// auto-generates a reverse mapping from 0 => B and 1 => C +enum Abc { + B, // = 0 + C, // = 1 + // "0" = "B", + // "1" = "C", +} +``` + +Computed enum definition + +```ts +enum C { + D = "e" + "f", // "ef" +} +``` + +## `Even` + +#### Signature + +```ts ignore +export type Even = Cast; +``` + +Branded type representing an even number or bigint. Used by overloads of the +[`isEven`](#iseven "Jump to symbol: 'isEven'") function to differentiate between +odd and even numbers. + +##### Type Parameters + +- **`T`** extends `Numeric` (default: `Numeric`) + +--- + +###### Category + +`Numeric` + +## `Exclusivity` + +#### Signature + +```ts ignore +export type Exclusivity = AnyRange[2]; +``` + +## `Falsy` + +#### Signature + +```ts ignore +export type Falsy = null | undefined | void | false | 0 | 0n | "" | NaN; +``` + +A type that represents all falsy values. + +###### Category + +`Primitives` + +## `Finite` + +#### Signature + +```ts ignore +export type Finite = Cast; +``` + +Casts a value into a finite type. If the value is not a number, it will resolve +to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `Float` + +#### Signature + +```ts ignore +export type Float = Cast; +``` + +Casts a value into a floating-point type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float` `number` + +#### Examples + +```ts +import { type Float, isFloat } from "@nick/is/float"; + +let x = 1.5 as Float, y = 0; + +if (isFloat(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float'. +``` + +## `Float16` + +#### Signature + +```ts ignore +export type Float16 = Cast; +``` + +Casts a value into a 16-bit floating-point type (half-precision). + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float16` `number` + +#### Examples + +```ts +import { type Float16, isFloat16 } from "@nick/is/float16"; + +let i = 1.5 as Float16, y = 0; + +if (isFloat16(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = 1; // <- TS2322 Type '1' is not assignable to type 'Float16'. +``` + +## `Float32` + +#### Signature + +```ts ignore +export type Float32 = Cast; +``` + +Casts a value into a floating-point type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float32` `number` + +#### Examples + +```ts +import { type Float32, isFloat32 } from "@nick/is/float32"; + +let x = 1.5 as Float32, y = 0; + +if (isFloat32(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float32'. +``` + +## `Float64` + +#### Signature + +```ts ignore +export type Float64 = Cast; +``` + +Casts a value into a float64-precision floating-point type. If the value is not +a number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float64` `number` + +#### Examples + +```ts +import { type Float64, isFloat64 } from "jsr:@type/number/float64"; + +let x = 1.5 as Float64, y = 0; + +if (isFloat64(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float64'. +``` + +## `Identifier` + +#### Signature + +```ts ignore +export type Identifier = Brand; +``` + +Utility type brand that represents a valid JavaScript identifier. This is a +string that can be used as a name of a variable, function, property, label, or +export. It is a subtype of `string` and is used to distinguish between regular +strings and identifiers. + +##### Type Parameters + +- **`T`** extends `string` (default: `string`) + +--- + +###### Category + +`Primitives` + +## `Infinity` + +#### Signature + +```ts ignore +export type Infinity = PositiveInfinity | NegativeInfinity; +``` + +Special type representing either positive or negative infinity. + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` + +## `InRange` + +#### Signature + +```ts ignore +export type InRange< + N extends number, + Min extends number = number, + Max extends number = number, + Tex extends Exclusivity = Exclusivity, +> = + & (number extends N ? IsInRange + : `${Min}|${Max}` extends `-${number}|-${number}` + ? `${N}` extends `-${number}` ? IsInRange : never + : `${Min}|${Max}` extends `${number}|-${number}` ? never + : `${Min}|${Max}` extends `-${number}|${number}` + ? `${N}` extends `-${number}` ? IsInRange : never + : `${N}` extends `-${number}` ? never + : IsInRange) + & N; +``` + +Type-level equivalent to the [`inRange`](#inrange "Jump to symbol: 'inRange'") +function, which (naively) checks if a number is within a given range. The range +can be specified in multiple ways, with one of four different exclusivity types. + +##### Type Parameters + +- **`N`** extends `number` +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `Exclusivity`) + +--- + +###### See Also + +- [`inRange`](#inrange "Jump to symbol: 'inRange'") for more information. + +## `Int16` + +#### Signature + +```ts ignore +export type Int16 = Cast; +``` + +Casts a value into a signed 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/int16"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -32769; // <- TS2322 Type '-32769' is not assignable to type 'Int16'. +``` + +## `Int32` + +#### Signature + +```ts ignore +export type Int32 = Cast; +``` + +Casts a value into a signed 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int32` `number` + +#### Examples + +```ts +import { type Int32, isInt32 } from "jsr:@type/number/int32"; + +let value = 1 as Int32; + +const setValue = (newValue: Int32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -2147483649; // <- TS2322 Type '-2147483649' is not assignable to type 'Int32'. +``` + +## `Int8` + +#### Signature + +```ts ignore +export type Int8 = Cast; +``` + +Casts a value into a signed 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int8` `number` + +#### Examples + +```ts +import { type Int8, isInt8 } from "@nick/is/int8"; + +let i = 1 as Int8, y = 0; + +if (isInt8(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = 1.5; // <- TS2322 Type '1.5' is not assignable to type 'Int8'. +``` + +## `Integer` + +#### Signature + +```ts ignore +export type Integer = N extends bigint + ? `${N}` extends `${infer I extends number}` ? N & Integer : never + : N extends number + ? number extends N ? N & INTEGER + : `${N}` extends `${bigint}` ? N & INTEGER : never + : never; +``` + +Casts a value into an integer type. If the value is not an number, or is a +non-integral number like 3.14, it will resolve to `never`. + +**Note**: once a value is cast to a type with this narrow of a constraint, +TypeScript's compiler will refuse any assignment to it that is not _exactly_ +compatible with the type. If you find yourself encountering errors about +incompatible types, try using the +[MaybeInteger](#maybeinteger "Jump to symbol: 'MaybeInteger'") type instead. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { type Integer, isInteger } from "jsr:@type/number"; + +function add(a: Integer, b: Integer) { + return (a + b) as Integer; +} + +let x = 1 as Integer, y = 2 as Integer, z = 3; + +if (isInteger(z)) { + console.log(add(add(x, y), z)); +} else { + console.log(add(x, y)); +} + +// These will raise TypeScript compiler errors: +add(x, z); +add(y, 3); + +// This level of strictness can be a bit silly in the wrong application: +x = 1; // <- TS4321 (`MaybeInteger` would be a better choice here) +``` + +## `IsEven` + +#### Signature + +```ts ignore +export type IsEven = `${T}` extends + `${"" | bigint}${1 | 3 | 5 | 7 | 9}` ? True : False; +``` + +Type-level equivalent of [`isEven`](#iseven "Jump to symbol: 'isEven'"), which +checks if a given numeric type (number or bigint) ends in an even number. +Returns [True](#true "Jump to symbol: 'True'") if so, and +[False](#false "Jump to symbol: 'False'") otherwise. + +##### Type Parameters + +- **`T`** extends `Numeric` +- **`True`** (default: `T`) +- **`False`** (default: `never`) + +--- + +###### Category + +`Numeric` + +## `IsOdd` + +#### Signature + +```ts ignore +export type IsOdd = + `${number}` extends `${T}` ? True + : `${bigint}` extends `${T}` ? True + : `${T}` extends `${infer _}${1 | 3 | 5 | 7 | 9}` ? True + : False; +``` + +Type-level equivalent of [`isOdd`](#isodd "Jump to symbol: 'isOdd'"), which +checks if a given numeric type (number or bigint) ends in an odd number. Returns +[True](#true "Jump to symbol: 'True'") if so, and +[False](#false "Jump to symbol: 'False'") otherwise. + +##### Type Parameters + +- **`T`** extends `Numeric` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Numeric` + +## `IsWhitespace` + +#### Signature + +```ts ignore +export type IsWhitespace = + IsNever extends true ? False + : IsAny extends true ? True : T extends Whitespace ? True + : T extends `${Whitespace}${infer R}` ? IsWhitespace + : False; +``` + +If the given string [`T`](#t "Jump to symbol: 'T'") is whitespace, this type +will resolve to the [`True`](#true "Jump to symbol: 'True'") type parameter +(default: `true`). Otherwise, it will resolve to the +[`False`](#false "Jump to symbol: 'False'") type parameter (default: `false`). + +##### Type Parameters + +- **`T`** extends `string` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +###### Tags + +`whitespace` + +## `IsWhitespaceChar` + +#### Signature + +```ts ignore +export type IsWhitespaceChar = + T extends Whitespace ? True : False; +``` + +Type-level predicate that checks if a given string +[`T`](#t "Jump to symbol: 'T'") is a whitespace character. If +[`T`](#t "Jump to symbol: 'T'") is a whitespace character, it will resolve to +the [`True`](#true "Jump to symbol: 'True'") type parameter (default: `true`). +Otherwise, it will resolve to the [`False`](#false "Jump to symbol: 'False'") +type parameter (default: `false`). + +The compile-time equivalent of the +[`isWhitespaceChar`](#iswhitespacechar "Jump to symbol: 'isWhitespaceChar'") +function. + +##### Type Parameters + +- **`T`** extends `string` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +## `IsWhitespaceCode` + +#### Signature + +```ts ignore +export type IsWhitespaceCode = + T extends WhitespaceCode ? True : False; +``` + +Type-level predicate that checks if a given string +[`T`](#t "Jump to symbol: 'T'") is a whitespace character code. If +[`T`](#t "Jump to symbol: 'T'") is a whitespace character code, it will resolve +to the [`True`](#true "Jump to symbol: 'True'") type parameter (default: +`true`). Otherwise, it will resolve to the +[`False`](#false "Jump to symbol: 'False'") type parameter (default: `false`). + +The compile-time equivalent of the +[`isWhitespaceCode`](#iswhitespacecode "Jump to symbol: 'isWhitespaceCode'") +function. + +##### Type Parameters + +- **`T`** extends `number` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +## `IterableObject` + +#### Signature + +```ts ignore +export type IterableObject = Iterable & object; +``` + +Represents an object that is also an iterable. This is the type of arrays, maps, +sets, and objects with a Symbol.iterator method. It is a subtype of both +`Iterable` and `object`. This is also the type that the function +[isIterableObject](#isiterableobject "Jump to symbol: 'isIterableObject'") +narrows its inputs to. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +###### Category + +`Iterables` + +## `MaybeFinite` + +#### Signature + +```ts ignore +export type MaybeFinite = Cast; +``` + +Casts a value into a partial finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeFloat16` + +#### Signature + +```ts ignore +export type MaybeFloat16 = Cast; +``` + +Casts a value into a partial 16-bit floating-point type (half-precision). + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float16` `number` + +## `MaybeFloat32` + +#### Signature + +```ts ignore +export type MaybeFloat32 = Cast; +``` + +Casts a value into a partial floating-point type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float32` `number` + +#### Examples + +```ts +import { isFloat32, type MaybeFloat32 } from "@nick/is/float32"; + +let x = 1.5 as MaybeFloat32, y = 0; + +if (isFloat32(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Float32`) +``` + +## `MaybeFloat64` + +#### Signature + +```ts ignore +export type MaybeFloat64 = Cast; +``` + +Casts a value into a partial float64-precision floating-point type. If the value +is not a number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float64` `number` + +#### Examples + +```ts +import { isFloat64, type MaybeFloat64 } from "jsr:@type/number/float64"; + +let x = 1.5 as MaybeFloat64, y = 0; + +if (isFloat64(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Float64`) +``` + +## `MaybeInt16` + +#### Signature + +```ts ignore +export type MaybeInt16 = Cast; +``` + +Casts a value into a partial signed 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/int16"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +value = -32769; // Error: Type '-32769' is not assignable to type 'Int16'. +``` + +## `MaybeInt32` + +#### Signature + +```ts ignore +export type MaybeInt32 = Cast; +``` + +Casts a value into a partial signed 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int32` `number` + +#### Examples + +```ts +import { isInt32, type MaybeInt32 } from "jsr:@type/number/int32"; + +let value = 1 as MaybeInt32; + +const setValue = (newValue: MaybeInt32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! +value = -2147483649; // <- No error! (this is the main difference from `Int32`) +``` + +## `MaybeInt8` + +#### Signature + +```ts ignore +export type MaybeInt8 = Cast; +``` + +Casts a value into a partial signed 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int8` `number` + +#### Examples + +```ts +import { isInt8, type MaybeInt8 } from "@nick/is/int8"; + +let i = 1 as MaybeInt8, y = 0; + +if (isInt8(i)) { + console.log(i); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Int8`) +``` + +## `MaybeInteger` + +#### Signature + +```ts ignore +export type MaybeInteger = N extends bigint + ? `${N}` extends `${infer I extends number}` ? N & MaybeInteger : never + : N extends number + ? number extends N ? N & MAYBE_INTEGER + : `${N}` extends `${bigint}` ? N & MAYBE_INTEGER + : never + : never; +``` + +Casts a value into a partial integer type. If the value is not an number, or is +a non-integral number like 3.14, it will resolve to `never`. This type is nearly +identical to [Integer](#integer "Jump to symbol: 'Integer'"), except it allows +assignment of values that are not precisely compatible with the type, while +still providing an extra level of type safety over the base `number` type. + +Once a value is cast to a type of this constraint, TypeScript's compiler will +refuse any incompatible assignment to it. To demonstrate, consider this example: + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { + isInteger, + type MaybeFloat, + type MaybeInteger, +} from "jsr:@type/number"; + +function add(a: MaybeInteger, b: MaybeInteger) { + return (a + b) as MaybeInteger; +} + +let x = 1 as MaybeInteger, y = 2 as MaybeInteger, z = 3; +let xx = 1.1 as MaybeFloat, yy = 2.2 as MaybeFloat, zz = 3.3; + +if (isInteger(z)) { + console.log(add(add(x, y), z)); +} else { + console.log(add(x, y)); +} + +// These will raise TypeScript compiler errors: +add(x, yy); // <- TS2345 Type 'MaybeFloat' is not assignable to type 'MaybeInteger'. +y = yy; // <- TS2322 Type 'MaybeFloat' is not assignable to type 'MaybeInteger'. + +y = 2; // <- No error! (this is the main difference from `Integer`) +``` + +## `MaybeNegative` + +#### Signature + +```ts ignore +export type MaybeNegative = Cast; +``` + +Casts a value into a partial negative type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Types` `Numbers` + +###### Tags + +`maybe` `negative` `number` + +#### Examples + +```ts +import { isNegative, type MaybeNegative } from "jsr:@type/number"; + +let x = -1 as MaybeNegative, y = 0; + +if (isNegative(x)) { + console.log(x); +} else { + console.log(y); +} + +y = -1; // <- No error! (this is the main difference from `Negative`) +``` + +## `MaybeNegativeFinite` + +#### Signature + +```ts ignore +export type MaybeNegativeFinite = Cast; +``` + +Casts a value into a partial negative finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeNegativeNonZero` + +#### Signature + +```ts ignore +export type MaybeNegativeNonZero = Cast< + N, + MAYBE_NEGATIVE & MAYBE_NON_ZERO +>; +``` + +Casts a value into a partial negative nonzero type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeNegativeNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybeNegativeNonZeroFinite = Cast< + N, + MAYBE_NEGATIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a partial negative nonzero finite type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeNegativeZero` + +#### Signature + +```ts ignore +export type MaybeNegativeZero = Cast; +``` + +Casts a value into a partial negative zero type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero, type MaybeNegativeZero } from "jsr:@type/number"; + +let x = -0 as MaybeNegativeZero, y = 0; + +if (isNegativeZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = -0; // <- No error! (this is the main difference from `NegativeZero`) +``` + +## `MaybeNonZero` + +#### Signature + +```ts ignore +export type MaybeNonZero = Cast; +``` + +Casts a value into a partial nonzero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero, type MaybeNonZero } from "jsr:@type/number"; + +let x = 1 as MaybeNonZero, y = 0; + +if (isNonZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `NonZero`) +``` + +## `MaybeNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybeNonZeroFinite = Cast; +``` + +Casts a value into a partial nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +## `MaybePositive` + +#### Signature + +```ts ignore +export type MaybePositive = Cast; +``` + +Casts a value into a partial positive type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `positive` `number` + +#### Examples + +```ts +import { isPositive, type MaybePositive } from "jsr:@type/number"; + +let x = 1 as MaybePositive, y = 0; + +if (isPositive(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Positive`) +``` + +## `MaybePositiveFinite` + +#### Signature + +```ts ignore +export type MaybePositiveFinite = Cast; +``` + +Casts a value into a partial positive finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybePositiveNonZero` + +#### Signature + +```ts ignore +export type MaybePositiveNonZero = Cast< + N, + MAYBE_POSITIVE & MAYBE_NON_ZERO +>; +``` + +Casts a value into a partial positive nonzero type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybePositiveNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybePositiveNonZeroFinite = Cast< + N, + MAYBE_POSITIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a partial positive nonzero finite type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybePositiveZero` + +#### Signature + +```ts ignore +export type MaybePositiveZero = Cast; +``` + +Casts a value into a partial positive zero type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero, type MaybePositiveZero } from "jsr:@type/number"; + +let x = 0 as MaybePositiveZero, y = 1; + +if (isPositiveZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 0; // <- No error! (this is the main difference from `PositiveZero`) +``` + +## `MaybeUint16` + +#### Signature + +```ts ignore +export type MaybeUint16 = Cast; +``` + +Casts a value into a partial unsigned 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `MaybeUint32` + +#### Signature + +```ts ignore +export type MaybeUint32 = Cast; +``` + +Casts a value into a partial unsigned 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `MaybeUint8` + +#### Signature + +```ts ignore +export type MaybeUint8 = Cast; +``` + +Casts a value into a partial unsigned 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint8, type MaybeUint8 } from "@nick/is/uint8"; + +let i = 1 as MaybeUint8, y = 0; + +if (isUint8(i)) { + console.log(i); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Uint8`) +``` + +## `MaybeZero` + +#### Signature + +```ts ignore +export type MaybeZero = Cast; +``` + +Casts a value into a partial zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isZero, type MaybeZero } from "jsr:@type/number"; + +let x = 0 as MaybeZero, y = 1; + +if (isZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 0; // <- No error! (this is the main difference from `Zero`) +``` + +## `NaN` + +#### Signature + +```ts ignore +export type NaN = Cast; +``` + +Casts a value into a branded type that represents the special numeric value +`NaN` (not a number). This is a very strict type, and it prevents any other type +from being assigned unless they pass the +[`isNaN`](#isnan "Jump to symbol: 'isNaN'") type guard. If the value is not a +subtype of `number`, this will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNan, type NaN } from "jsr:@type/number"; + +let x = NaN as NaN, y = 0; + +if (isNan(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NaN'. +``` + +## `Negative` + +#### Signature + +```ts ignore +export type Negative = Cast; +``` + +Casts a value into a negative type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`negative` `number` + +#### Examples + +```ts +import { isNegative, type Negative } from "jsr:@type/number"; + +let x = -1 as Negative, y = 0; + +if (isNegative(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'Negative'. +``` + +## `NegativeBigInteger` + +#### Signature + +```ts ignore +export type NegativeBigInteger = CastInt; +``` + +Casts a value into a negative big integer type. If the value is not a bigint or +a string containing a valid integer, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `NegativeFinite` + +#### Signature + +```ts ignore +export type NegativeFinite = Cast; +``` + +Casts a value into a negative finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeFiniteInteger` + +#### Signature + +```ts ignore +export type NegativeFiniteInteger = Cast< + N, + NEGATIVE & FINITE & INTEGER +>; +``` + +Casts a value into a negative finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeInfinity` + +#### Signature + +```ts ignore +export type NegativeInfinity = -Infinity; +``` + +Special type representing negative infinity (`Number.NEGATIVE_INFINITY`). + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` `negative` + +## `NegativeInteger` + +#### Signature + +```ts ignore +export type NegativeInteger = Cast; +``` + +Casts a value into a negative integer type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZero` + +#### Signature + +```ts ignore +export type NegativeNonZero = Cast; +``` + +Casts a value into a negative nonzero type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZeroFinite` + +#### Signature + +```ts ignore +export type NegativeNonZeroFinite = Cast< + N, + NEGATIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a negative nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type NegativeNonZeroFiniteInteger = Cast< + N, + NEGATIVE & NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a negative nonzero finite integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZeroInteger` + +#### Signature + +```ts ignore +export type NegativeNonZeroInteger = Cast< + N, + NEGATIVE & NON_ZERO & INTEGER +>; +``` + +Casts a value into a negative nonzero integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeZero` + +#### Signature + +```ts ignore +export type NegativeZero = Cast; +``` + +Casts a value into a negative zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero, type NegativeZero } from "jsr:@type/number"; + +let x = -0 as NegativeZero, y = 0; + +if (isNegativeZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NegativeZero'. +``` + +## `NonEmptyArray` + +#### Signature + +```ts ignore +export type NonEmptyArray = [T, ...T[]]; +``` + +Represents an array with 1 or more element of the specific type `T`. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +###### Category + +`Indexed Collections` + +## `NonZero` + +#### Signature + +```ts ignore +export type NonZero = Cast; +``` + +Casts a value into a nonzero type. If the value is not a number, it will resolve +to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero, type NonZero } from "jsr:@type/number"; + +let x = 1 as NonZero, y = 0; + +if (isNonZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NonZero'. +``` + +## `NonZeroFinite` + +#### Signature + +```ts ignore +export type NonZeroFinite = Cast; +``` + +Casts a value into a nonzero finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type NonZeroFiniteInteger = Cast< + N, + NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a nonzero finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NonZeroInteger` + +#### Signature + +```ts ignore +export type NonZeroInteger = Cast; +``` + +Casts a value into a nonzero integer type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `Odd` + +#### Signature + +```ts ignore +export type Odd = Cast< + IsOdd, Extract, never>, + ODD +>; +``` + +Branded type representing an odd number. Used by overloads of the +[`isOdd`](#isodd "Jump to symbol: 'isOdd'") function to differentiate between +odd and even numbers. + +##### Type Parameters + +- **`T`** (default: `number`) + +--- + +###### Category + +`Numeric` + +## `Positive` + +#### Signature + +```ts ignore +export type Positive = Cast; +``` + +Casts a value into a positive type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive, type Positive } from "jsr:@type/number"; + +let x = 1 as Positive, y = 0; + +if (isPositive(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'Positive'. +``` + +## `PositiveBigInteger` + +#### Signature + +```ts ignore +export type PositiveBigInteger = CastInt; +``` + +Casts a value into a positive big integer type. If the value is not a bigint or +a string containing a valid integer, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `PositiveFinite` + +#### Signature + +```ts ignore +export type PositiveFinite = Cast; +``` + +Casts a value into a positive finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveFiniteInteger` + +#### Signature + +```ts ignore +export type PositiveFiniteInteger = Cast< + N, + POSITIVE & FINITE & INTEGER +>; +``` + +Casts a value into a positive finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveInfinity` + +#### Signature + +```ts ignore +export type PositiveInfinity = Infinity; +``` + +Special type representing positive infinity (`Number.POSITIVE_INFINITY`). + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` `positive` + +## `PositiveInteger` + +#### Signature + +```ts ignore +export type PositiveInteger = Cast; +``` + +Casts a value into a positive finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZero` + +#### Signature + +```ts ignore +export type PositiveNonZero = Cast; +``` + +Casts a value into a positive nonzero type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZeroFinite` + +#### Signature + +```ts ignore +export type PositiveNonZeroFinite = Cast< + N, + POSITIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a positive nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type PositiveNonZeroFiniteInteger = Cast< + N, + POSITIVE & NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a positive nonzero finite integer type. If the value is not a +number, it will resolve to `never`.s + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZeroInteger` + +#### Signature + +```ts ignore +export type PositiveNonZeroInteger = Cast< + N, + POSITIVE & NON_ZERO & INTEGER +>; +``` + +Casts a value into a positive nonzero integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveZero` + +#### Signature + +```ts ignore +export type PositiveZero = Cast; +``` + +Casts a value into a positive zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero, type PositiveZero } from "jsr:@type/number"; + +let x = 0 as PositiveZero, y = 1; + +if (isPositiveZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'PositiveZero'. +``` + +## `Primitive` + +#### Signature + +```ts ignore +export type Primitive = + | string + | number + | bigint + | boolean + | symbol + | null + | undefined; +``` + +Represents a primitive value. This includes strings, numbers, bigints, booleans, +symbols, null, and undefined. + +###### Category + +`Primitives` + +## `Printable` + +#### Signature + +```ts ignore +export type Printable = string | number | bigint | boolean | null | undefined; +``` + +Represents a value that can be printed in a template literal type string, which +means it is either a `string`, `number`, `bigint`, `boolean`, `null` or +`undefined`. Any other type of value will raise a compiler error if you attempt +to construct a template literal type with it. + +#### Examples + +```ts +import type { Printable } from "jsr:@nick/is/printable"; + +type Join = T extends + [infer F extends Printable, ...infer R] + ? `${F}${R extends [] ? "" : D}${Join}` + : ""; + +type Result = Join<[1, "two", 3n, true, null, undefined]>; +// ^? type Result = "1two3true" +``` + +## `Range` + +#### Signature + +```ts ignore +export type Range< + Min extends number = number, + Max extends number = number, + Tex extends Exclusivity = never, +> = [Tex] extends [never] + ? + | RangeInclusiveMin + | RangeInclusive + | RangeInclusiveMax + | RangeExclusive + | RangeUnknown + : Either< + Extract, Required>>, + RangeUnknown + >; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `never`) + +--- + +## `RegisteredSymbol` + +#### Signature + +```ts ignore +export type RegisteredSymbol = Brand; +``` + +Branded type representing a symbol that is registered in the global symbol +registry, which means it was created using the `Symbol.for()` function. This +kind of symbol is **not** allowed as keys in Weak Collections like `WeakMap` or +`WeakSet` objects, as they are not truly unique. + +This is the type that the +[`isRegisteredSymbol`](#isregisteredsymbol "Jump to symbol: 'isRegisteredSymbol'") +type guard narrows its input values to. It is provided as an export for you to +use in tandem with that type guard, to ensure your code is handling registered +symbols in a strict, type-safe manner. + +###### Categories + +`Primitives` `Types` + +#### Examples + +```ts +import { + isRegisteredSymbol, + type RegisteredSymbol, +} from "jsr:@nick/is/registered-symbol"; + +function doSomething(key: RegisteredSymbol): void { + // ... +} + +const key = Symbol.for("foo"); +if (isRegisteredSymbol(key)) { + doSomething(key); +} +``` + +```ts +import { + isRegisteredSymbol, + type RegisteredSymbol, +} from "jsr:@nick/is/registered-symbol"; + +function assertRegisteredSymbol( + value: unknown, +): asserts value is RegisteredSymbol { + if (!isRegisteredSymbol(value)) { + throw new Error("Expected a registered symbol."); + } +} +``` + +## `SemVer` + +#### Signature + +```ts ignore +export type SemVer = Brand; +``` + +Represents a validated Semantic Version (SemVer v2.0.0) string. This is the type +the [`isSemVer`](#issemver "Jump to symbol: 'isSemVer'") function narrows its +input values to. + +###### Category + +`Strings` + +## `SupportedSetLike` + +#### Signature + +```ts ignore +export type SupportedSetLike = + Exclude, keyof SetLike> extends + keyof globalThis.Set ? ExtendedSetLike : SetLike; +``` + +This type represents either the full +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +interface, or the [`SetLike`](#setlike "Jump to symbol: 'SetLike'") interface, +depending on whether the current environment supports composition methods +introduced by the TC39 Set Methods Proposal. + +If the current environment supports the composition methods, this type will +resolve to the +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +interface. Otherwise, it will resolve to the +[`SetLike`](#setlike "Jump to symbol: 'SetLike'") interface. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +###### See Also + +- [`SupportedSetLikeConstructor`](#supportedsetlikeconstructor "Jump to symbol: 'SupportedSetLikeConstructor'") + for a similar type that represents the constructor function for the supported + set-like object. + +## `SupportedSetLikeConstructor` + +#### Signature + +```ts ignore +export type SupportedSetLikeConstructor = + Exclude extends + keyof globalThis.SetConstructor ? ExtendedSetLikeConstructor + : SetLikeConstructor; +``` + +This type represents either the full +[`ExtendedSetLikeConstructor`](#extendedsetlikeconstructor "Jump to symbol: 'ExtendedSetLikeConstructor'") +interface, or the +[`SetLikeConstructor`](#setlikeconstructor "Jump to symbol: 'SetLikeConstructor'") +interface, depending on whether the current environment supports composition +methods introduced by the TC39 Set Methods Proposal. + +If the current environment supports the composition methods, this type will +resolve to the +[`ExtendedSetLikeConstructor`](#extendedsetlikeconstructor "Jump to symbol: 'ExtendedSetLikeConstructor'") +interface. Otherwise, it will resolve to the +[`SetLikeConstructor`](#setlikeconstructor "Jump to symbol: 'SetLikeConstructor'") +interface. + +###### See Also + +- [`SupportedSetLike`](#supportedsetlike "Jump to symbol: 'SupportedSetLike'") + for a similar type that represents the full set-like object. + +## `TypedArray` + +#### Signature + +```ts ignore +export type TypedArray = + InstanceType>; +``` + +Represents an instance of a typed array, which is a view over a raw binary data +buffer (e.g. `ArrayBuffer`) of a fixed-size. The following are the supported +native typed array types: + +- `Uint8Array` +- `Uint8ClampedArray` +- `Uint16Array` +- `Uint32Array` +- `Int8Array` +- `Int16Array` +- `Int32Array` +- `Float16Array` (ES2024) +- `Float32Array` +- `Float64Array` +- `BigInt64Array` +- `BigUint64Array` + +##### Type Parameters + +- **`T`** extends `ArrayBufferLike` (default: `ArrayBufferLike`) + +--- + +###### Category + +`Binary Data Structures` + +###### See Also + +- [isTypedArray](#istypedarray "Jump to symbol: 'isTypedArray'") to check if a + value is this type at runtime. + +## `Uint16` + +#### Signature + +```ts ignore +export type Uint16 = Cast; +``` + +Casts a value into an unsigned 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `Uint32` + +#### Signature + +```ts ignore +export type Uint32 = Cast; +``` + +Casts a value into an unsigned 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `Uint8` + +#### Signature + +```ts ignore +export type Uint8 = Cast; +``` + +Casts a value into an unsigned 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint8, type Uint8 } from "@nick/is/uint8"; + +let i = 1 as Uint8, y = 0; + +if (isUint8(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint8'. +``` + +## `UniqueSymbol` + +#### Signature + +```ts ignore +export type UniqueSymbol = Brand; +``` + +Branded type representing a unique symbol, which is a primitive symbol that was +created using the `Symbol()` function, and is not a registered symbol created +with `Symbol.for()`, nor a well-known symbol defined on the global `Symbol` +object. + +###### Category + +`Primitives` + +## `Unwrap` + +#### Signature + +```ts ignore +export type Unwrap = U extends Cast ? [N, T] : [U, never]; +``` + +Unwraps a type that has been cast with [Cast](#cast "Jump to symbol: 'Cast'") +into a tuple of the original value and the specific type it was cast to (or +"branded" with). If the given type was _not_ cast with +[Cast](#cast "Jump to symbol: 'Cast'"), it will resolve to a tuple containing +the original value and `never`, respectively. + +##### Type Parameters + +- **`U`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { Cast, Unwrap } from "jsr:@nick/is/number"; + +type Int_3 = Cast<3, INTEGER>; + +function unwrap(value: T): Unwrap[0] { + return value as Unwrap[0]; +} +``` + +## `WellKnownSymbol` + +#### Signature + +```ts ignore +export type WellKnownSymbol = ValueOf<{ + [K in [object Object]]: SymbolConstructor[K] + }>; +``` + +Union type representing all of the well-known symbols defined on the global +`Symbol` object in the current runtime environment. + +###### Category + +`Primitives` + +## `Whitespace` + +#### Signature + +```ts ignore +export type Whitespace = typeof WHITESPACE_CHARS[number] & {}; +``` + +A union of all whitespace characters, as defined by the Unicode standard. This +includes characters such as spaces, tabs, newlines, and additional Unicode +whitespace characters that are not typically visible in text. + +This type is particularly useful for type-level programming, specifically when +developing string manipulation types that need to account for various types of +whitespace characters rather than a simple ASCII space. + +For example, if one wanted to create a type-level utility to split a string +literal into its constituent parts using whitespace and punctuation as its +delimiters, it could be done quite easily using this type. + +###### Category + +`Types` + +###### Tags + +`whitespace` + +## `WhitespaceCode` + +#### Signature + +```ts ignore +export type WhitespaceCode = typeof WHITESPACE_CODES[number]; +``` + +Union of all whitespace character codes, as defined by the Unicode standard. +This includes characters such as spaces, tabs, newlines, and additional Unicode +whitespace characters that are not typically visible. + +###### Category + +`Types` + +###### Tags + +`whitespace` `char code` + +## `WhitespaceLike` + +#### Signature + +```ts ignore +export type WhitespaceLike = WhitespaceString | Whitespace | WhitespaceCode; +``` + +A union type that can be either a string or a whitespace character code. + +This is the type used in the +[`isWhitespaceLike`](#iswhitespacelike "Jump to symbol: 'isWhitespaceLike'") +function to determine if a value is either a string or a whitespace character +code. + +###### Category + +`Types` + +###### Tags + +`whitespace` + +## `WhitespaceString` + +#### Signature + +```ts ignore +export type WhitespaceString = S & WhitespaceBrand; +``` + +Represents a string that has been verified at runtime to only consist of +whitespace characters. This is a nominal (branded) type that is distinct from a +regular string type. + +##### Type Parameters + +- **`S`** extends `string` (default: `string`) + +--- + +###### Category + +`Types` + +###### Tags + +`whitespace` `branded` + +## `Zero` + +#### Signature + +```ts ignore +export type Zero = Cast; +``` + +Casts a value into a zero type. If the value is not a number, it will resolve to +`never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isZero, type Zero } from "jsr:@type/number/zero"; + +let x = 0 as Zero, y = 1; + +if (isZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Zero'. +``` + +## `ArrayIterator` + +Represents a array iterator. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +##### Extends `IterableIterator` + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "Array Iterator"; +``` + +--- + +## `AsyncFunction` + +##### Type Parameters + +- **`TReturn`** (default: `any`) + +--- + +### Call Signatures + +```ts +(...args: any[]): Promise; +``` + +--- + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "AsyncFunction"; +``` + +--- + +## `Class` + +###### Category + +`Types` + +#### Examples + +```ts +import { isClass } from "jsr:@nick/is/class"; + +class Foo {} +console.log(isClass(Foo)); // true + +const Bar = function () { + this.foo = "bar"; + return this; +}; +console.log(isClass(Bar)); // false + +const Baz = () => {}; +console.log(isClass(Baz)); // false +``` + +##### Type Parameters + +- **`T`** (default: `any`) +- **`A`** extends `readonly unknown[]` (default: `readonly any[]`) +- **`P`** extends `object | null` (default: `Is`) + +--- + +### Properties + +#### prototype + +```ts +readonly prototype: P; +``` + +--- + +## `Closer` + +An abstract interface which when implemented provides an interface to close +files/resources that were previously opened. + +###### Category + +`I/O` + +### Methods + +#### close + +```ts +close(): void; +``` + +Closes the resource, "freeing" the backing file/resource. + +--- + +## `Constructor` + +Represents a constructor function that creates instances of type `T`. + +###### Category + +`Types` + +##### Type Parameters + +- **`T`** (default: `unknown`) +- **`A`** extends `readonly unknown[]` (default: `readonly unknown[]`) + +--- + +### Properties + +#### prototype + +```ts +readonly prototype: Prototype; +``` + +--- + +## `EnumLike` + +Represents an "enum-like" object, which is a plain object composed of either all +string keys and string values, or a two-way mapping of string keys to numeric +values (and vice versa). + +This is a supertype of the type of object created by TypeScript's builtin `enum` +keyword. Its primary consumer is the +[`isEnum`](#isenum "Jump to symbol: 'isEnum'") function. + +###### Category + +`Types` + +###### Tags + +`enum` `objects` + +#### Examples + +```ts +// when we create an enum with constant numeric values, the TypeScript +// compiler auto-generates an implicit reverse-mapping from the values +// back to their respective keys, providing us with the capability to +// access the keys by their values. +enum Priority { + Low = 0x0, + Medium = 0x1, + High = 0x2, + Insane = 0xFF, +} + +// the actual object generated by the enum syntax above looks like this: +const Priority = { + Low: 0, + Medium: 1, + High: 2, + Insane: 255, + "0": "Low", + "1": "Medium", + "2": "High", + "255": "Insane", +} satisfies EnumLike; + +// this provides us with the ability to access a key even when we only have +// its value, a language feature that is popular in other OOP languages such +// as C#, Java, and C++: + +console.log(Priority.High); // 2 +console.log(Priority[2]); // "High" +console.assert(Priority.High === Priority[Priority[2]]); +console.assert(Priority[2] === Priority[Priority.High]); +``` + +##### Type Parameters + +- **`K`** extends `string | number` (default: `string | number`) +- **`V`** extends `string | number` (default: `string | number`) + +--- + +### Index Signatures + +#### EnumLike + +```ts +readonly [key: string]: K | V | undefined +``` + +#### EnumLike + +```ts +readonly [index: number]: K +``` + +--- + +## `ExtendedSetLike` + +A `ExtendedSetLike` object is a collection of values, where each value may only +occur once. The values in a `ExtendedSetLike` can be either primitive values or +object references. The keys of a `ExtendedSetLike` are the same as the values. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +##### Extends `SetLike` + +### Methods + +#### union + +```ts +union( + other: ReadonlyCollection, + ): ExtendedSetLike; +``` + +##### Parameters + +| Name | Info | +| :---------- | :------------------------------------------------ | +| **`other`** | The other set-like object to merge with this one. | + +##### Returns + +a new [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object containing all the elements in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +and also all the elements in the [`other`](#other "Jump to symbol: 'other'"). + +#### intersection + +```ts +intersection( + other: ReadonlyCollection, + ): ExtendedSetLike; +``` + +##### Parameters + +| Name | Info | +| :---------- | :---------------------------------------------------- | +| **`other`** | The other set-like object to intersect with this one. | + +##### Returns + +a new [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object containing all the elements which are both in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +and in the [`other`](#other "Jump to symbol: 'other'"). + +#### difference + +```ts +difference( + other: ReadonlyCollection, + ): ExtendedSetLike; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a new [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object containing all the elements in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +which are not also in the [`other`](#other "Jump to symbol: 'other'"). + +#### symmetricDifference + +```ts +symmetricDifference( + other: ReadonlyCollection, + ): ExtendedSetLike; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a new ExtendedSetLike object containing all the elements which are in either +this [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object or in the [`other`](#other "Jump to symbol: 'other'"), but not in both. + +#### isSubsetOf + +```ts +isSubsetOf( + other: ReadonlyCollection, + ): boolean; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a boolean indicating whether all the elements in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +are also in the [`other`](#other "Jump to symbol: 'other'"). + +#### isSupersetOf + +```ts +isSupersetOf( + other: ReadonlyCollection, + ): boolean; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a boolean indicating whether all the elements in the +[`other`](#other "Jump to symbol: 'other'") are also in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object. + +#### isDisjointFrom + +```ts +isDisjointFrom( + other: ReadonlyCollection, + ): boolean; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a boolean indicating whether this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +has no elements in common with the [`other`](#other "Jump to symbol: 'other'"). + +--- + +## `ExtendedSetLikeConstructor` + +Represents a constructor function for an +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object. + +### Properties + +#### prototype + +```ts +readonly prototype: ExtendedSetLike; +``` + +--- + +## `MapIterator` + +Represents a map iterator. + +##### Type Parameters + +- **`K`** +- **`V`** + +--- + +##### Extends `IterableIterator<[K,V]>` + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "Map Iterator" | "Map Entries"; +``` + +--- + +## `MapLike` + +Map-like objects are collections of keys and values, where each key may only +appear once in the collection. + +###### Category + +`Types` + +##### Type Parameters + +- **`K`** +- **`V`** + +--- + +##### Extends `Iterable<[K,V]>` + +### Properties + +#### size + +```ts +readonly size: number; +``` + +Gets the number of elements in the collection. + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: string; +``` + +--- + +### Methods + +#### has + +```ts +has(key: K): boolean; +``` + +Tests whether a key is present in the collection. + +##### Parameters + +| Name | Info | +| :-------- | :----------------- | +| **`key`** | The key to lookup. | + +##### Returns + +`true` if the key is present in the collection; otherwise, `false`. + +#### get + +```ts +get(key: K): V | undefined; +``` + +Gets the value associated with the provided key, if it exists. + +##### Parameters + +| Name | Info | +| :-------- | :----------------- | +| **`key`** | The key to lookup. | + +##### Returns + +The value associated with the provided key, or `undefined`. + +#### set + +```ts +set(key: K, value: V): this; +``` + +Sets the value in the collection associated with the provided key. + +##### Parameters + +| Name | Info | +| :---------- | :---------------- | +| **`key`** | The key to set. | +| **`value`** | The value to set. | + +##### Returns + +The collection. + +#### clear + +```ts +clear(): void; +``` + +Removes all entries from the collection. + +#### delete + +```ts +delete(key: K): boolean; +``` + +Removes a key from the collection. + +##### Parameters + +| Name | Info | +| :-------- | :----------------- | +| **`key`** | The key to remove. | + +##### Returns + +`true` if the delete operation was successful, otherwise `false`. + +#### keys + +```ts +keys(): IterableIterator; +``` + +Returns an `IterableIterator` for the keys present in the collection. + +#### values + +```ts +values(): IterableIterator; +``` + +Returns an `IterableIterator` for the values present in the collection. + +#### entries + +```ts +entries(): IterableIterator< + [K, V] + >; +``` + +Returns an `IterableIterator` for the entries present in the collection. Each +entry is a tuple containing the key and value for each element. + +#### forEach + +```ts +forEach( + cb: (this: This, value: V, key: K, map: MapLike) => void, + thisArg?: This, + ): void; +``` + +Executes a provided function once per each key/value pair in the collection. + +##### Parameters + +| Name | Info | +| :------------ | :------------------------------------------------------ | +| **`cb`** | The callback to execute. | +| **`thisArg`** | The value to use as `this` when executing the callback. | + +##### Returns + +Nothing. + +#### [Symbol.iterator] + +```ts +[Symbol.iterator](): IterableIterator< + [K, V] + >; +``` + +Returns an `IterableIterator` for the entries present in the collection. + +--- + +## `MapLikeConstructor` + +A constructor function for creating new `MapLike` objects. + +###### Category + +`Types` + +### Properties + +#### prototype + +```ts +readonly prototype: MapLike; +``` + +--- + +## `Reader` + +An abstract interface which when implemented provides an interface to read bytes +into an array buffer asynchronously. + +###### Category + +`I/O` + +### Methods + +#### read + +```ts +read( + p: Uint8Array, + ): Promise; +``` + +Reads up to `p.byteLength` bytes into `p`. It resolves to the number of bytes +read (`0` < `n` <= `p.byteLength`) and rejects if any error encountered. Even if +`read()` resolves to `n` < `p.byteLength`, it may use all of `p` as scratch +space during the call. If some data is available but not `p.byteLength` bytes, +`read()` conventionally resolves to what is available instead of waiting for +more. + +When `read()` encounters end-of-file condition, it resolves to EOF (null). When +`read()` encounters an error, it rejects with an error. + +Callers should always process the `n` > `0` bytes returned before considering +the EOF (`null`). Doing so correctly handles I/O errors that happen after +reading some bytes and also both of the allowed EOF behaviors. + +Implementations should not retain a reference to `p`. + +--- + +## `ReaderSync` + +An abstract interface which when implemented provides an interface to read bytes +into an array buffer synchronously. + +###### Category + +`I/O` + +### Methods + +#### readSync + +```ts +readSync( + p: Uint8Array, + ): number | null; +``` + +Reads up to `p.byteLength` bytes into `p`. It resolves to the number of bytes +read (`0` < `n` <= `p.byteLength`) and rejects if any error encountered. Even if +`readSync()` returns `n` < `p.byteLength`, it may use all of `p` as scratch +space during the call. If some data is available but not `p.byteLength` bytes, +`readSync()` conventionally returns what is available instead of waiting for +more. + +When `readSync()` encounters end-of-file condition, it returns EOF (`null`). + +When `readSync()` encounters an error, it throws with an error. + +Callers should always process the `n` > `0` bytes returned before considering +the EOF (`null`). Doing so correctly handles I/O errors that happen after +reading some bytes and also both of the allowed EOF behaviors. + +Implementations should not retain a reference to `p`. + +--- + +## `ReadonlyCollection` + +Set-like objects are collections of unique values (each value may only occur +once). The `ReadonlyCollection` interface defines the bare minimum requirements +for an object to be considered "set-like" in JavaScript; that is, it must have: + +- a `has` method, which tests whether a given value is present in the set, + returning a boolean value indicating the result. +- a `keys` method, which returns an `IterableIterator` for the keys present in + the set. Since set collections are keyed by their values, the `keys` method + actually iterates over the **_values_** in the set. +- a read-only `size` property (getter), which returns the number of values in + the set at any given time. + +This interface the base for the `SetLike` interface (hence its name), which +extends it with additional methods like `add`, `delete`, `clear`, `forEach`, +`values`, and `entries` to provide a more complete API for working with Set- +like collections in JavaScript. Prior to the TC39 Proposal for Set Methods, the +`SetLike` interface was the shape of the native `Set` API in JavaScript. + +Following the introduction of the TC39 Proposal for Set Methods, the methods for +set composition (`union`, `intersection`, `difference`, etc.) were added to the +`Set` API, which necessitated the creation of the `ExtendedSetLike` interface to +represent the full API for set-like collections in JavaScript. + +Those methods require their arguments to implement the +[`ReadonlyCollection`](#readonlycollection "Jump to symbol: 'ReadonlyCollection'") +interface, rather than the full +[`SetLike`](#setlike "Jump to symbol: 'SetLike'") or +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'"). This +means you can call `Set.prototype.union` with a `Set`, `Map`, or even an +`IterableWeakSet` object, since they all implement the `ReadonlyCollection` API. + +###### See Also + +- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +### Properties + +#### size + +```ts +readonly size: number; +``` + +##### Returns + +The number of elements in the collection. + +--- + +### Methods + +#### has + +```ts +has(value: T): boolean; +``` + +Tests whether a given value is present in the collection. + +##### Parameters + +| Name | Info | +| :---------- | :------------------- | +| **`value`** | The value to lookup. | + +##### Returns + +`true` if the value is in the collection; otherwise, `false`. + +#### keys + +```ts +keys(): IterableIterator; +``` + +Gets an `IterableIterator` for the keys present in the collection. + +##### Returns + +An iterator of the keys in the collection. + +--- + +## `ReadonlyCollectionConstructor` + +Represents a constructor function for a +[`ReadonlyCollection`](#readonlycollection "Jump to symbol: 'ReadonlyCollection'") +object, which is the base implementation of a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object, without any of the additional composition methods like `union` or +`intersection`. + +###### See Also + +- [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") for + the full interface with composition methods. +- [`SetLike`](#setlike "Jump to symbol: 'SetLike'") for the core interface + without composition methods. + +### Properties + +#### prototype + +```ts +readonly prototype: ReadonlyCollection; +``` + +--- + +## `SetIterator` + +Represents a set iterator. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +##### Extends `IterableIterator` + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "Set Iterator" | "Set Entries"; +``` + +--- + +## `SetLike` + +Represents the core functionality of a `SetLike` object, which is the base +implementation of a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object, without any additional composition methods (`union`, `intersection`, +`difference`, etc). This was the native `Set` API prior to the TC39 Set Methods +Proposal's introduction. + +###### See Also + +- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set +- [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") for + the full interface with composition methods. +- [`SetLikeConstructor`](#setlikeconstructor "Jump to symbol: 'SetLikeConstructor'") + for the constructor interface. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +##### Extends `Iterable`, `ReadonlyCollection` + +### Properties + +#### size + +```ts +readonly size: number; +``` + +##### Returns + +The number of elements in the collection. + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: string; +``` + +--- + +### Methods + +#### add + +```ts +add(value: T): this; +``` + +Adds the given value to the collection, if it does not already exist. + +##### Parameters + +| Name | Info | +| :---------- | :---------------- | +| **`value`** | The value to add. | + +##### Returns + +The collection. + +#### has + +```ts +has(value: T): boolean; +``` + +Tests whether a key is present in the collection. + +##### Parameters + +| Name | Info | +| :---------- | :----------------- | +| **`value`** | The key to lookup. | + +##### Returns + +`true` if the value is in the collection; otherwise, `false`. + +#### clear + +```ts +clear(): void; +``` + +Removes all values from the collection. + +#### delete + +```ts +delete(value: T): boolean; +``` + +Removes a value from the collection. + +##### Parameters + +| Name | Info | +| :---------- | :------------------- | +| **`value`** | The vakue to remove. | + +##### Returns + +`true` if the operation was successful; otherwise, `false`. + +#### forEach + +```ts +forEach( + cb: (this: This, value: T, value2: T, set: this) => void, + thisArg?: This, + ): void; +``` + +Executes a provided function once per each entry in the collection. The callback +is invoked with the current value for both the first and second arguments (to +maintain a similar signature as `forEach` on other iterable objects like `Map` +and `Array`). + +##### Parameters + +| Name | Info | +| :------------ | :------------------------------------------------------ | +| **`cb`** | The callback to execute. | +| **`thisArg`** | The value to use as `this` when executing the callback. | + +##### Returns + +Nothing. + +#### keys + +```ts +keys(): IterableIterator; +``` + +##### Returns + +an Iterable of the values in the collection. + +#### values + +```ts +values(): IterableIterator; +``` + +##### Returns + +an `IterableIterator` for the values present in the collection. + +#### entries + +```ts +entries(): IterableIterator< + [T, T] + >; +``` + +##### Returns + +an `IterableIterator` of the entries present in the collection. Each entry is a +tuple containing the key and value for each element. + +#### [Symbol.iterator] + +```ts +[Symbol.iterator](): IterableIterator< + T + >; +``` + +Returns an iterator of the [`values`](#values "Jump to symbol: 'values'") in the +set. + +--- + +## `SetLikeConstructor` + +Represents a constructor function for a +[`SetLike`](#setlike "Jump to symbol: 'SetLike'") object, which is the base +implementation of a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object, without any of the additional composition methods like `union` or +`intersection`. + +###### See Also + +- [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") for + the full interface with composition methods. +- [`SetLike`](#setlike "Jump to symbol: 'SetLike'") for the core interface + without composition methods. + +### Properties + +#### prototype + +```ts +readonly prototype: SetLike; +``` + +--- + +## `StringIterator` + +Represents a string iterator. + +##### Type Parameters + +- **`T`** extends `string` (default: `string`) + +--- + +##### Extends `IterableIterator[number]>` + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "String Iterator"; +``` + +--- + +## `TemplateObject` + +A template strings object is an object with a `raw` property containing an array +of strings. This type is used to loosely represent the first argument passed to +a tagged template function, which is a template strings array. + +Note: while all `TemplateStringsArray` values are `TemplateObject`s, not all +`TemplateObject`s are `TemplateStringsArray`s. + +###### Category + +`Template Literals` + +### Properties + +#### raw + +```ts +readonly raw: readonly string[]; +``` + +--- + +## `TemplateStringsArray` + +A template strings array is an array of strings with an own property named `raw` +that is also an array of strings. This is the type of array provided to tagged +template literals for the first argument, and is represented as the type +`TemplateStringsArray` in TypeScript. + +Note: while all `TemplateStringsArray` values are `TemplateStringsObject`s, not +all `TemplateStringsObject`s are `TemplateStringsArray`s. + +###### Category + +`Types` + +###### Tags + +`TemplateStringsArray` + +##### Extends `ReadonlyArray` + +### Properties + +#### raw + +```ts +readonly raw: ReadonlyArray; +``` + +--- + +## `Writer` + +An abstract interface which when implemented provides an interface to write +bytes from an array buffer to a file/resource asynchronously. + +###### Category + +`I/O` + +### Methods + +#### write + +```ts +write( + p: Uint8Array, + ): Promise; +``` + +Writes `p.byteLength` bytes from `p` to the underlying data stream. It resolves +to the number of bytes written from `p` (`0` <= `n` <= `p.byteLength`) or reject +with the error encountered that caused the write to stop early. `write()` must +reject with a non-null error if would resolve to `n` < `p.byteLength`. `write()` +must not modify the slice data, even temporarily. + +This function is one of the lowest level APIs and most users should not work +with this directly, but rather use +[`writeAll()`](https://deno.land/std/streams/write_all.ts?s=writeAll) from +`std/streams/write_all.ts` instead. + +Implementations should not retain a reference to `p`. + +--- + +## `WriterSync` + +An abstract interface which when implemented provides an interface to write +bytes from an array buffer to a file/resource synchronously. + +###### Category + +`I/O` + +### Methods + +#### writeSync + +```ts +writeSync( + p: Uint8Array, + ): number; +``` + +Writes `p.byteLength` bytes from `p` to the underlying data stream. It returns +the number of bytes written from `p` (`0` <= `n` <= `p.byteLength`) and any +error encountered that caused the write to stop early. `writeSync()` must throw +a non-null error if it returns `n` < `p.byteLength`. `writeSync()` must not +modify the slice data, even temporarily. + +Implementations should not retain a reference to `p`. + +--- diff --git a/docs/non-array-object.md b/docs/non-array-object.md new file mode 100644 index 0000000..2928a4a --- /dev/null +++ b/docs/non-array-object.md @@ -0,0 +1,185 @@ +# @nick/is/non-array-object + +## `isNonArrayObject` + +#### Signature + +```ts ignore +function isNonArrayObject(it: T): it is NonArrayObject; +``` + +Check if the given value is a non-null object. This includes all non-null and +non-array values where `typeof === "object"`. If you want to check for arrays +and functions, too, use +[isObjectLike](#isobjectlike "Jump to symbol: 'isObjectLike'") instead. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a non-null object, `false` otherwise. + +###### Category + +`Objects` + +#### Examples + +```ts +import { isNonArrayObject } from "jsr:@nick/is/non-array-object"; + +console.log(isNonArrayObject({})); // true +console.log(isNonArrayObject(new class {}())); // true +console.log(isNonArrayObject(new Object())); // true +``` + +## `isNonArrayObject` + +#### Signature + +```ts ignore +function isNonArrayObject(it: unknown): it is Record; +``` + +Check if the given value is a non-null object. This includes all non-null and +non-array values where `typeof === "object"`. If you want to check for arrays +and functions, too, use +[isObjectLike](#isobjectlike "Jump to symbol: 'isObjectLike'") instead. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a non-null object, `false` otherwise. + +###### Category + +`Objects` + +#### Examples + +```ts +import { isNonArrayObject } from "jsr:@nick/is/non-array-object"; + +console.log(isNonArrayObject({})); // true +console.log(isNonArrayObject(new class {}())); // true +console.log(isNonArrayObject(new Object())); // true + +console.log(isNonArrayObject([])); // false +console.log(isNonArrayObject(() => {})); // false +console.log(isNonArrayObject(null)); // false +console.log(isNonArrayObject(undefined)); // false +console.log(isNonArrayObject(1)); // false +``` + +## `isNonArrayObject` + +#### Signature + +```ts ignore +function isNonArrayObject(it: unknown): it is NonArrayObject; +``` + +## `AsNonArrayObject` + +#### Signature + +```ts ignore +export type AsNonArrayObject = IsAnyOrUnknownOrNever< + T, + never, + IsArray< + T, + never, + NonArrayObject< + IsExact< + T, + object, + T, + T extends (...args: any) => any ? never : T + > + > + > +>; +``` + +Converts a given type `T` into a non-array object type, if possible. If `T` is +`any`, `unknown`, or `never`, it resolves to `never`. If `T` is an array or a +function, it also resolves to `never`. If `T` is an object type, it resolves to +`NonArrayObject`, branding it with the unique symbol that marks it as a valid +non-array object. + +##### Type Parameters + +- **`T`** + +--- + +###### Category + +`Objects` + +###### Tags + +`NonArrayObject` `branded` + +## `NonArrayObject` + +#### Signature + +```ts ignore +export type NonArrayObject = + & IsAnyOrUnknownOrNever< + T, + Record, + Exclude + > + & NonArrayObjectBrand; +``` + +Represents a non-null object that is neither an array nor a function. This is +**generic** nominal (branded) type, that can either be used as is to represent a +non-null object that is neither an array nor a function, or can be parameterized +with a specific type. + +When parameterized, the type it receives will be intersected with an unforgeable +unique brand to ensure it is distinct from the base type (and any other type for +that matter). This allows you to create custom subtypes of your own that have +been validated at runtime, providing a level of type safety that is just not +possible with a plain object type. + +##### Type Parameters + +- **`T`** (default: `EmptyObject`) + +--- + +###### Category + +`Objects` + +###### Tags + +`NonArrayObject` `branded` + +#### Examples + +```ts +import nonArray, { type NonArrayObject } from "jsr:@nick/is/non-array-object"; + +let obj: readonly unknown[] | Record = {}; + +const doesntLikeArrays = (obj: NonArrayObject) => { + // do something with obj +}; + +doesntLikeArrays(obj); // error +``` diff --git a/docs/non-empty-array.md b/docs/non-empty-array.md new file mode 100644 index 0000000..ebe0a3e --- /dev/null +++ b/docs/non-empty-array.md @@ -0,0 +1,106 @@ +# @nick/is/non-empty-array + +## `isNonEmptyArray` + +#### Signature + +```ts ignore +function isNonEmptyArray( + a: MaybeArray, + test?: Predicate, +): a is NonEmptyArray; +``` + +Checks if the given value is an array with at least one element of a specific +type. + +##### Parameters + +| Name | Info | +| :--------- | :------------------------------------------------------ | +| **`it`** | The value to check. | +| **`test`** | The type guard to check the type of the array elements. | + +##### Returns + +`true` if the value is an array with at least one element of the specific type +(if a `test` predicate is provided), `false` otherwise. + +###### Category + +`Indexed Collections` + +#### Examples + +```ts +import { isNonEmptyArray } from "jsr:@nick/is/array"; + +console.log(isNonEmptyArray([])); // false +console.log(isNonEmptyArray([1, 2, 3])); // true +console.log(isNonEmptyArray({})); // false +``` + +```ts +import { isNonEmptyArray } from "jsr:@nick/is/array"; +import { isString } from "jsr:@nick/is/string"; +import { isNumber } from "jsr:@nick/is/number"; +import { expectType } from "jsr:@nick/is/type/expect"; + +const arr: unknown[] = ["a", "b", "c"]; + +if (isNonEmptyArray(arr, isString)) { + console.log(arr, "is an array of strings"); + // ^? const arr: readonly [string, ...string[]] + expectType(arr); +} else if (isNonEmptyArray(arr, isNumber)) { + console.log(arr, "is an array of numbers"); + // ^? const arr: readonly [number, ...number[]] + expectType(arr); +} else { + console.log(arr, "is not an array of strings or numbers"); + // ^? const arr: readonly unknown[] + expectType(arr); +} +``` + +## `isNonEmptyArray` + +#### Signature + +```ts ignore +function isNonEmptyArray( + a: unknown, + test?: Predicate, +): a is NonEmptyArray; +``` + +## `isNonEmptyArray` + +#### Signature + +```ts ignore +function isNonEmptyArray( + a: unknown, + test?: Predicate, +): a is NonEmptyArray; +``` + +## `NonEmptyArray` + +#### Signature + +```ts ignore +export type NonEmptyArray = [T, ...T[]]; +``` + +Represents an array with 1 or more element of the specific type `T`. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +###### Category + +`Indexed Collections` diff --git a/docs/null.md b/docs/null.md new file mode 100644 index 0000000..ea9c92b --- /dev/null +++ b/docs/null.md @@ -0,0 +1,37 @@ +# @nick/is/null + +## `isNull` + +#### Signature + +```ts ignore +function isNull(it: unknown): it is null; +``` + +Checks if the value is `null`, and nothing else. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `null`, or `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isNull } from "jsr:@nick/is/null"; + +isNull(null); // true +isNull(undefined); // false +isNull(0); // false +isNull(""); // false +isNull(false); // false +``` diff --git a/docs/number-object.md b/docs/number-object.md new file mode 100644 index 0000000..dcc0188 --- /dev/null +++ b/docs/number-object.md @@ -0,0 +1,45 @@ +# @nick/is/number-object + +## `isNumberObject` + +#### Signature + +```ts ignore +function isNumberObject(it: unknown): it is Number; +``` + +Checks if a value is a Number object, which is a boxed-primitive number that was +created either with the `new Number()` syntax, or by wrapping a primitive number +in the `Object()` wrapper function. + +Boxed primitives are strongly discouraged in JavaScript, as they can lead to all +sorts of unexpected behavior and performance issues. As such, this function - +and the other boxed primitive functions like it - are provided for your +convenience, to help you easily ensure your code is not on the receiving end of +such behavior. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a boxed-primitive number object; otherwise, `false`. + +###### Category + +`Boxed Primitives` + +#### Examples + +```ts +import { isNumberObject } from "jsr:@nick/is/number-object"; + +isNumberObject(Object(1)); // true +isNumberObject(new Number(1)); // true + +isNumberObject(Number(1)); // false +isNumberObject(1); // false +``` diff --git a/docs/number.md b/docs/number.md new file mode 100644 index 0000000..2bbc5bf --- /dev/null +++ b/docs/number.md @@ -0,0 +1,7376 @@ +# @nick/is/number + +## `inRange` + +#### Signature + +```ts ignore +function inRange< + V extends number, + R extends Derange, + Min extends number = R extends [infer M extends number, number, Exclusivity?] + ? M + : R[1] extends Exclusivity ? 0 + : R[0], + Max extends number = R extends [number, infer M extends number, Exclusivity?] + ? M + : R[1] extends Exclusivity ? R[0] + : R[1], + Tex extends Exclusivity = Either< + R extends [number, number, infer T extends Exclusivity] ? T + : R[1] extends Exclusivity ? R[1] + : undefined, + "[)" + >, +>(value: V, ...range: [...R] | Derange): value is InRange; +``` + +Checks if a given number is within a given range. The range can be specified in +multiple ways: + +- As a tuple with the minimum and maximum values, and optional exclusivity + string of either "[]", "(]", "[)", or "()". +- As a tuple with a maximum value and an optional exclusivity string. This + assumes a minimum value of `0`. +- As a single number, which is assumed to be the maximum value, with an assumed + minimum value of `0` and an assumed exclusivity string of "[]". + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------- | +| **`value`** | The number to check. | +| **`range`** | The range to check against. | + +##### Returns + +`true` if the number is within the range, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { inRange } from "jsr:@nick/is/number/in_range"; + +console.log(inRange(1, 0, 2)); // true +console.log(inRange(1, 2, 0)); // false +console.log(inRange(1, 2)); // true +console.log(inRange(1, 2, "(]")); // true +``` + +## `inRange` + +#### Signature + +```ts ignore +function inRange(value: number, ...range: Derange): value is InRange; +``` + +Checks if a given number is within a given range. The range can be specified in +multiple ways: + +- As a tuple with the minimum and maximum values, and optional exclusivity + string of either "[]", "(]", "[)", or "()". +- As a tuple with a maximum value and an optional exclusivity string. This + assumes a minimum value of `0`. +- As a single number, which is assumed to be the maximum value, with an assumed + minimum value of `0` and an assumed exclusivity string of "[]". + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------- | +| **`value`** | The number to check. | +| **`range`** | The range to check against. | + +##### Returns + +`true` if the number is within the range, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { inRange } from "jsr:@nick/is/number/in_range"; + +console.log(inRange(1, 0, 2)); // true +console.log(inRange(1, 2, 0)); // false +console.log(inRange(1, 2)); // true +console.log(inRange(1, 2, "(]")); // true +``` + +## `inRange` + +#### Signature + +```ts ignore +function inRange(value: number, ...range: any[]): undefined; +``` + +## `isEven` + +#### Signature + +```ts ignore +function isEven(it: T): IsEven; +``` + +Checks if a given number / bigint is an even number. Returns `true` if it is +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :----------------------------------------------------------------- | +| **`it`** | The number or bigint to check, either literal or in string format. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEven` + +#### Signature + +```ts ignore +function isEven(it: number | `${number}`): it is Even; +``` + +Checks if a given number / numeric string is even. Returns `true` if the value +is divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------- | +| **`it`** | The number or numeric string to check. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEven` + +#### Signature + +```ts ignore +function isEven(it: bigint | `${bigint}`): it is Even; +``` + +Checks if a given bigint or bigint string is an even number. Returns `true` if +the value is divisible by `2`, and `false` otherwise. This usually corresponds +to integers that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------ | +| **`it`** | The bigint or bigint string to check. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEven` + +#### Signature + +```ts ignore +function isEven(it: unknown): it is Even; +``` + +Checks if a given number / bigint is even. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an even finite integer, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEvenNumber` + +#### Signature + +```ts ignore +function isEvenNumber(it: T): IsEven; +``` + +Checks if a given number / bigint is an even number. Returns `true` if it is +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :----------------------------------------------------------------- | +| **`it`** | The number or bigint to check, either literal or in string format. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEvenNumber` + +#### Signature + +```ts ignore +function isEvenNumber(it: number | `${number}`): it is Even; +``` + +Checks if a given number / numeric string is even. Returns `true` if the value +is divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------- | +| **`it`** | The number or numeric string to check. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEvenNumber` + +#### Signature + +```ts ignore +function isEvenNumber(it: bigint | `${bigint}`): it is Even; +``` + +Checks if a given bigint or bigint string is an even number. Returns `true` if +the value is divisible by `2`, and `false` otherwise. This usually corresponds +to integers that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------ | +| **`it`** | The bigint or bigint string to check. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEvenNumber` + +#### Signature + +```ts ignore +function isEvenNumber(it: unknown): it is Even; +``` + +Checks if a given number / bigint is even. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an even finite integer, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isExclusivity` + +#### Signature + +```ts ignore +function isExclusivity(it: unknown): it is Exclusivity; +``` + +Checks if a given value is a valid range exclusivity string (either "[]", "(]", +"[)", or "()"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a valid range exclusivity string, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isExclusivity } from "jsr:@nick/is/number/in_range"; + +console.log(isExclusivity("[]")); // true +console.log(isExclusivity("(]")); // true +console.log(isExclusivity("[)")); // true +console.log(isExclusivity("()")); // true +console.log(isExclusivity("")); // false +console.log(isExclusivity("[")); // false +console.log(isExclusivity("]")); // false +``` + +## `isFinite` + +#### Signature + +```ts ignore +function isFinite(it: N): it is Finite; +``` + +Checks if a given value is a finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFinite } from "jsr:@nick/is/integer"; + +console.log(isFinite(0)); // true +console.log(isFinite(1)); // true +console.log(isFinite(-1)); // true +console.log(isFinite(1.5)); // true +console.log(isFinite(NaN)); // false +console.log(isFinite(Infinity)); // false +``` + +## `isFinite` + +#### Signature + +```ts ignore +function isFinite(it: unknown): it is Finite; +``` + +Checks if a given value is a finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFinite } from "jsr:@nick/is/integer"; + +console.log(isFinite(0)); // true +console.log(isFinite(1)); // true +console.log(isFinite(-1)); // true +console.log(isFinite(1.5)); // true +console.log(isFinite(NaN)); // false +console.log(isFinite(Infinity)); // false +``` + +## `isFiniteInteger` + +#### Signature + +```ts ignore +function isFiniteInteger(it: N): it is FiniteInteger; +``` + +Checks if a given value is a finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isFiniteInteger(0)); // true +console.log(isFiniteInteger(1)); // true +console.log(isFiniteInteger(-1)); // true +console.log(isFiniteInteger(1.5)); // false +console.log(isFiniteInteger(NaN)); // false +console.log(isFiniteInteger(Infinity)); // false +``` + +## `isFiniteInteger` + +#### Signature + +```ts ignore +function isFiniteInteger(it: unknown): it is FiniteInteger; +``` + +Checks if a given value is a finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isFiniteInteger(0)); // true +console.log(isFiniteInteger(1)); // true +console.log(isFiniteInteger(-1)); // true +console.log(isFiniteInteger(1.5)); // false +console.log(isFiniteInteger(NaN)); // false +console.log(isFiniteInteger(Infinity)); // false +``` + +## `isFiniteNumber` + +#### Signature + +```ts ignore +function isFiniteNumber(it: N): it is Finite; +``` + +Checks if a given value is a finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFinite } from "jsr:@nick/is/integer"; + +console.log(isFinite(0)); // true +console.log(isFinite(1)); // true +console.log(isFinite(-1)); // true +console.log(isFinite(1.5)); // true +console.log(isFinite(NaN)); // false +console.log(isFinite(Infinity)); // false +``` + +## `isFiniteNumber` + +#### Signature + +```ts ignore +function isFiniteNumber(it: unknown): it is Finite; +``` + +Checks if a given value is a finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFinite } from "jsr:@nick/is/integer"; + +console.log(isFinite(0)); // true +console.log(isFinite(1)); // true +console.log(isFinite(-1)); // true +console.log(isFinite(1.5)); // true +console.log(isFinite(NaN)); // false +console.log(isFinite(Infinity)); // false +``` + +## `isFloat` + +#### Signature + +```ts ignore +function isFloat(it: N): it is Float; +``` + +Checks if the value is a floating-point number. Supports both single and double +precision floating-point numbers. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a floating-point number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat } from "@nick/is/float"; + +isFloat(1); // false +isFloat(1.0); // false +isFloat(1.1); // true +isFloat(1.00001e1); // true +``` + +## `isFloat` + +#### Signature + +```ts ignore +function isFloat(it: unknown): it is Float; +``` + +Checks if the value is a floating-point number. Supports both single and double +precision floating-point numbers. + +## Rules for what is (and isn't) seen as a floating-point number + +- `0`, `-0` are considered valid floating-point numbers, and return `true`. +- `1`, `-1` and other integers (or _"non-floating"_ values) return `false`. +- Special cases like `Infinity`, `-Infinity`, and `NaN` return `false`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a floating-point number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat } from "@nick/is/float"; + +isFloat(0); // true +isFloat(1); // false +isFloat(1.0); // false +isFloat(1.1); // true +isFloat(1.00001e1); // true +``` + +## `isFloat16` + +#### Signature + +```ts ignore +function isFloat16(it: N): it is Float16; +``` + +Checks if a value is a 16-bit half-precision floating-point number, also known +as `float16` or `binary16`, as defined by the IEEE 754 standard. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a half-precision floating-point number. Otherwise +`false`. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat16 } from "@nick/is/float16"; + +isFloat16(1); // true +isFloat16(1.5); // true +isFloat16(3.140625); // true +isFloat16(NaN); // false +isFloat16(1.1); // false +isFloat16(Math.PI); // false +isFloat16(Infinity); // false +``` + +## `isFloat16` + +#### Signature + +```ts ignore +function isFloat16(it: unknown): it is Float16; +``` + +Checks if a value is a 16-bit half-precision floating-point number, also known +as `float16` or `binary16`, as defined by the IEEE 754 standard. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a half-precision floating-point number. Otherwise +`false`. + +###### Category + +`Numbers` + +## `isFloat16` + +#### Signature + +```ts ignore +function isFloat16(it: any): it is Float16; +``` + +## `isFloat32` + +#### Signature + +```ts ignore +function isFloat32(it: N): it is Float32; +``` + +Checks if the value is a floating-point number. Supports single-precision +floating-point numbers. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a single-precision floating-point number, otherwise +`false`. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat32 } from "@nick/is/float32"; + +isFloat32(1); // false +isFloat32(1.0); // false +isFloat32(1.1); // true +isFloat32(1.00001e1); // true +``` + +## `isFloat32` + +#### Signature + +```ts ignore +function isFloat32(it: unknown): it is Float32; +``` + +Checks if the value is a floating-point number. Supports single-precision +floating-point numbers. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a single-precision floating-point number, otherwise +`false`. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat32 } from "@nick/is/float32"; + +isFloat32(1); // false +isFloat32(1.0); // false +isFloat32(1.1); // true +isFloat32(1.00001e1); // true +``` + +## `isFloat64` + +#### Signature + +```ts ignore +function isFloat64(it: N): it is Float64; +``` + +Checks if the value is a float64-precision floating-point number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a float64-precision floating-point number, `false` +otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat64 } from "jsr:@nick/is/float64"; + +console.log(isFloat64(1.5)); // true +console.log(isFloat64(0)); // false +console.log(isFloat64(1)); // false +console.log(isFloat64(-1)); // false +console.log(isFloat64(NaN)); // false +console.log(isFloat64(Infinity)); // false +``` + +## `isFloat64` + +#### Signature + +```ts ignore +function isFloat64(it: unknown): it is Float64; +``` + +Checks if the value is a float64-precision floating-point number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a float64-precision floating-point number, `false` +otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat64 } from "jsr:@nick/is/float64"; + +console.log(isFloat64(1.5)); // true +console.log(isFloat64(0)); // false +console.log(isFloat64(1)); // false +console.log(isFloat64(-1)); // false +console.log(isFloat64(NaN)); // false +console.log(isFloat64(Infinity)); // false +``` + +## `isInfinity` + +#### Signature + +```ts ignore +function isInfinity(it: unknown): it is Infinity; +``` + +Checks if a given value is a non-finite number (`Infinity` or `-Infinity`). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a non-finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInfinity } from "@nick/is/number/infinity"; + +console.log(isInfinity(Infinity)); // true +console.log(isInfinity(-Infinity)); // true +console.log(isInfinity(1)); // false +console.log(isInfinity(-1)); // false +console.log(isInfinity(NaN)); // false +``` + +## `isInt16` + +#### Signature + +```ts ignore +function isInt16(it: unknown): it is Int16; +``` + +Checks if a value is a 16-bit integer (between -32768 and 32767). + +To check for an **unsigned** 16-bit integer (0-65535), use +[isUint16](#isuint16 "Jump to symbol: 'isUint16'"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/number"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -32769; // <- TS2322 Type '-32769' is not assignable to type 'Int16'. +``` + +## `isInt16` + +#### Signature + +```ts ignore +function isInt16(it: unknown): it is Int16; +``` + +Checks if a value is a 16-bit integer (between -32768 and 32767). + +To check for an **unsigned** 16-bit integer (0-65535), use +[isUint16](#isuint16 "Jump to symbol: 'isUint16'"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInt16 } from "@nick/is/number"; + +isInt16(32768); // false +isInt16(-32769); // false +isInt16(1); // true +isInt16(32767); // true +isInt16(-32768); // true +``` + +## `isInt32` + +#### Signature + +```ts ignore +function isInt32(it: N): it is Int32; +``` + +Checks if a given value is a signed 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a signed 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`int32` `number` + +#### Examples + +```ts +import { type Int32, isInt32, type MaybeInt32 } from "jsr:@type/number/int32"; + +let value = 1 as Int32; + +const setValue = (newValue: MaybeInt32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -2147483649; // <- TS2322 Type '-2147483649' is not assignable to type 'Int32'. +``` + +## `isInt32` + +#### Signature + +```ts ignore +function isInt32(it: unknown): it is Int32; +``` + +Checks if a given value is a signed 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a signed 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`int32` `number` + +#### Examples + +```ts +import { isInt32 } from "jsr:@type/number/int32"; + +console.log(isInt32(0x7FFFFFFF)); // <- true +console.log(isInt32(-2147483649)); // <- false +``` + +## `isInt8` + +#### Signature + +```ts ignore +function isInt8(it: N): it is Int8; +``` + +Checks if a given value is a signed 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a signed 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInt8 } from "@nick/is/int8"; + +isInt8(1); // true +isInt8(1.0); // false +isInt8(1.1); // false +isInt8(1.00001e1); // false +``` + +## `isInt8` + +#### Signature + +```ts ignore +function isInt8(it: unknown): it is Int8; +``` + +Checks if a given value is a signed 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a signed 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInt8 } from "@nick/is/int8"; + +console.log(isInt8(1)); // true +console.log(isInt8(1.0)); // false +console.log(isInt8(1.1)); // false +console.log(isInt8(1.00001e1)); // false +``` + +## `isInteger` + +#### Signature + +```ts ignore +function isInteger(it: N): it is Integer; +``` + +Checks if a given value is an integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInteger } from "jsr:@nick/is/integer"; + +console.log(isInteger(0)); // true +console.log(isInteger(1)); // true +console.log(isInteger(-1)); // true +console.log(isInteger(1.5)); // false +console.log(isInteger(NaN)); // false +console.log(isInteger(Infinity)); // false +``` + +## `isInteger` + +#### Signature + +```ts ignore +function isInteger(it: unknown): it is Integer; +``` + +Checks if a given value is an integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInteger } from "jsr:@nick/is/integer"; + +console.log(isInteger(0)); // true +console.log(isInteger(1)); // true +console.log(isInteger(-1)); // true +console.log(isInteger(1.5)); // false +console.log(isInteger(NaN)); // false +console.log(isInteger(Infinity)); // false +``` + +## `isNaN` + +#### Signature + +```ts ignore +function isNaN(it: N): it is NaN; +``` + +Checks if a given value is `NaN` (not a number). This is a type-safe alias of +the global `isNaN` function, + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `NaN`, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNaN } from "jsr:@type/number"; + +console.log(isNaN(0)); // false +console.log(isNaN(1)); // false +console.log(isNaN(1.5)); // false +console.log(isNaN(NaN)); // true +console.log(isNaN(Infinity)); // false +``` + +## `isNaN` + +#### Signature + +```ts ignore +function isNaN(it: unknown): it is NaN; +``` + +Checks if a given value is `NaN` (not a number). This is a type-safe alias of +the global `isNaN` function, + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `NaN`, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNaN } from "jsr:@type/number"; + +console.log(isNaN(0)); // false +console.log(isNaN(1)); // false +console.log(isNaN(1.5)); // false +console.log(isNaN(NaN)); // true +console.log(isNaN(Infinity)); // false +``` + +## `isNegative` + +#### Signature + +```ts ignore +function isNegative(it: N): it is Negative; +``` + +Checks if a given value is a negative number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`negative` + +#### Examples + +```ts +import { isNegative } from "jsr:@nick/is/integer"; + +console.log(isNegative(0)); // false +console.log(isNegative(1)); // false +console.log(isNegative(1.5)); // false +console.log(isNegative(NaN)); // false +console.log(isNegative(Infinity)); // false + +console.log(isNegative(-0)); // true +console.log(isNegative(-1)); // true +console.log(isNegative(-Infinity)); // true +``` + +## `isNegative` + +#### Signature + +```ts ignore +function isNegative(it: unknown): it is Negative; +``` + +Checks if a given value is a negative number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`negative` + +#### Examples + +```ts +import { isNegative } from "jsr:@nick/is/integer"; + +console.log(isNegative(0)); // false +console.log(isNegative(1)); // false +console.log(isNegative(1.5)); // false +console.log(isNegative(NaN)); // false +console.log(isNegative(Infinity)); // false + +console.log(isNegative(-0)); // true +console.log(isNegative(-1)); // true +console.log(isNegative(-Infinity)); // true +``` + +## `isNegativeFiniteInteger` + +#### Signature + +```ts ignore +function isNegativeFiniteInteger( + it: N, +): it is NegativeFiniteInteger; +``` + +Checks if a given value is a negative finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteInteger(0)); // false +console.log(isNegativeFiniteInteger(1)); // false +console.log(isNegativeFiniteInteger(-1)); // true +console.log(isNegativeFiniteInteger(1.5)); // false +console.log(isNegativeFiniteInteger(NaN)); // false +console.log(isNegativeFiniteInteger(Infinity)); // false +``` + +## `isNegativeFiniteInteger` + +#### Signature + +```ts ignore +function isNegativeFiniteInteger(it: unknown): it is NegativeFiniteInteger; +``` + +Checks if a given value is a negative finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteInteger(0)); // false +console.log(isNegativeFiniteInteger(1)); // false +console.log(isNegativeFiniteInteger(-1)); // true +console.log(isNegativeFiniteInteger(1.5)); // false +console.log(isNegativeFiniteInteger(NaN)); // false +console.log(isNegativeFiniteInteger(Infinity)); // false +``` + +## `isNegativeFiniteNumber` + +#### Signature + +```ts ignore +function isNegativeFiniteNumber(it: N): it is NegativeFinite; +``` + +Checks if a given value is a negative finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteNumber(0)); // false +console.log(isNegativeFiniteNumber(1)); // false +console.log(isNegativeFiniteNumber(-1)); // true +console.log(isNegativeFiniteNumber(1.5)); // false +console.log(isNegativeFiniteNumber(NaN)); // false +console.log(isNegativeFiniteNumber(Infinity)); // false +``` + +## `isNegativeFiniteNumber` + +#### Signature + +```ts ignore +function isNegativeFiniteNumber(it: unknown): it is NegativeFinite; +``` + +Checks if a given value is a negative finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteNumber(0)); // false +console.log(isNegativeFiniteNumber(1)); // false +console.log(isNegativeFiniteNumber(-1)); // true +console.log(isNegativeFiniteNumber(1.5)); // false +console.log(isNegativeFiniteNumber(NaN)); // false +console.log(isNegativeFiniteNumber(Infinity)); // false +``` + +## `isNegativeInfinity` + +#### Signature + +```ts ignore +function isNegativeInfinity(it: unknown): it is NegativeInfinity; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is negative infinity, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `negative` `infinity` + +#### Examples + +```ts +import { isNegativeInfinity } from "@nick/is/number/infinity"; + +console.log(isNegativeInfinity(Infinity)); // false +console.log(isNegativeInfinity(-Infinity)); // true +console.log(isNegativeInfinity(1)); // false +console.log(isNegativeInfinity(-1)); // false +console.log(isNegativeInfinity(NaN)); // false +``` + +## `isNegativeInteger` + +#### Signature + +```ts ignore +function isNegativeInteger(it: N): it is NegativeInteger; +``` + +Checks if a given value is a negative integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeInteger(0)); // false +console.log(isNegativeInteger(1)); // false +console.log(isNegativeInteger(-1)); // true +console.log(isNegativeInteger(1.5)); // false +console.log(isNegativeInteger(NaN)); // false +console.log(isNegativeInteger(Infinity)); // false +``` + +## `isNegativeInteger` + +#### Signature + +```ts ignore +function isNegativeInteger(it: unknown): it is NegativeInteger; +``` + +Checks if a given value is a negative integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeInteger(0)); // false +console.log(isNegativeInteger(1)); // false +console.log(isNegativeInteger(-1)); // true +console.log(isNegativeInteger(1.5)); // false +console.log(isNegativeInteger(NaN)); // false +console.log(isNegativeInteger(Infinity)); // false +``` + +## `isNegativeNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isNegativeNonZeroFiniteInteger( + it: N, +): it is NegativeNonZeroFiniteInteger; +``` + +Checks if a given value is a negative nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteInteger(0)); // false +console.log(isNegativeNonZeroFiniteInteger(1)); // false +console.log(isNegativeNonZeroFiniteInteger(-1)); // true +console.log(isNegativeNonZeroFiniteInteger(1.5)); // false +console.log(isNegativeNonZeroFiniteInteger(NaN)); // false +console.log(isNegativeNonZeroFiniteInteger(Infinity)); // false +``` + +## `isNegativeNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isNegativeNonZeroFiniteInteger( + it: unknown, +): it is NegativeNonZeroFiniteInteger; +``` + +Checks if a given value is a negative nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteInteger(0)); // false +console.log(isNegativeNonZeroFiniteInteger(1)); // false +console.log(isNegativeNonZeroFiniteInteger(-1)); // true +console.log(isNegativeNonZeroFiniteInteger(1.5)); // false +console.log(isNegativeNonZeroFiniteInteger(NaN)); // false +console.log(isNegativeNonZeroFiniteInteger(Infinity)); // false +``` + +## `isNegativeNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isNegativeNonZeroFiniteNumber( + it: N, +): it is NegativeNonZeroFinite; +``` + +Checks if a given value is a negative nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteNumber(0)); // false +console.log(isNegativeNonZeroFiniteNumber(1)); // false +console.log(isNegativeNonZeroFiniteNumber(-1)); // true +console.log(isNegativeNonZeroFiniteNumber(1.5)); // false +console.log(isNegativeNonZeroFiniteNumber(NaN)); // false +console.log(isNegativeNonZeroFiniteNumber(Infinity)); // false +``` + +## `isNegativeNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isNegativeNonZeroFiniteNumber( + it: unknown, +): it is NegativeNonZeroFinite; +``` + +Checks if a given value is a negative nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteNumber(0)); // false +console.log(isNegativeNonZeroFiniteNumber(1)); // false +console.log(isNegativeNonZeroFiniteNumber(-1)); // true +console.log(isNegativeNonZeroFiniteNumber(1.5)); // false +console.log(isNegativeNonZeroFiniteNumber(NaN)); // false +console.log(isNegativeNonZeroFiniteNumber(Infinity)); // false +``` + +## `isNegativeNonZeroInteger` + +#### Signature + +```ts ignore +function isNegativeNonZeroInteger( + it: N, +): it is NegativeNonZeroInteger; +``` + +Checks if a given value is a negative nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroInteger(0)); // false +console.log(isNegativeNonZeroInteger(1)); // false +console.log(isNegativeNonZeroInteger(-1)); // true +console.log(isNegativeNonZeroInteger(1.5)); // false +console.log(isNegativeNonZeroInteger(NaN)); // false +console.log(isNegativeNonZeroInteger(Infinity)); // true +``` + +## `isNegativeNonZeroInteger` + +#### Signature + +```ts ignore +function isNegativeNonZeroInteger(it: unknown): it is NegativeNonZeroInteger; +``` + +Checks if a given value is a negative nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroInteger(0)); // false +console.log(isNegativeNonZeroInteger(1)); // false +console.log(isNegativeNonZeroInteger(-1)); // true +console.log(isNegativeNonZeroInteger(1.5)); // false +console.log(isNegativeNonZeroInteger(NaN)); // false +console.log(isNegativeNonZeroInteger(Infinity)); // true +``` + +## `isNegativeNonZeroNumber` + +#### Signature + +```ts ignore +function isNegativeNonZeroNumber(it: N): it is NegativeNonZero; +``` + +Checks if a given value is a negative nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero number, `false` otherwise. + +#### Examples + +```ts +import { isNegativeNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroNumber(0)); // false +console.log(isNegativeNonZeroNumber(1)); // false +console.log(isNegativeNonZeroNumber(-1)); // true +console.log(isNegativeNonZeroNumber(1.5)); // false +console.log(isNegativeNonZeroNumber(NaN)); // false +console.log(isNegativeNonZeroNumber(Infinity)); // false +``` + +## `isNegativeNonZeroNumber` + +#### Signature + +```ts ignore +function isNegativeNonZeroNumber(it: unknown): it is NegativeNonZero; +``` + +Checks if a given value is a negative nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero number, `false` otherwise. + +#### Examples + +```ts +import { isNegativeNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroNumber(0)); // false +console.log(isNegativeNonZeroNumber(1)); // false +console.log(isNegativeNonZeroNumber(-1)); // true +console.log(isNegativeNonZeroNumber(1.5)); // false +console.log(isNegativeNonZeroNumber(NaN)); // false +console.log(isNegativeNonZeroNumber(Infinity)); // false +``` + +## `isNegativeNumber` + +#### Signature + +```ts ignore +function isNegativeNumber(it: N): it is Negative; +``` + +Checks if a given value is a negative number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`negative` + +#### Examples + +```ts +import { isNegative } from "jsr:@nick/is/integer"; + +console.log(isNegative(0)); // false +console.log(isNegative(1)); // false +console.log(isNegative(1.5)); // false +console.log(isNegative(NaN)); // false +console.log(isNegative(Infinity)); // false + +console.log(isNegative(-0)); // true +console.log(isNegative(-1)); // true +console.log(isNegative(-Infinity)); // true +``` + +## `isNegativeNumber` + +#### Signature + +```ts ignore +function isNegativeNumber(it: unknown): it is Negative; +``` + +Checks if a given value is a negative number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`negative` + +#### Examples + +```ts +import { isNegative } from "jsr:@nick/is/integer"; + +console.log(isNegative(0)); // false +console.log(isNegative(1)); // false +console.log(isNegative(1.5)); // false +console.log(isNegative(NaN)); // false +console.log(isNegative(Infinity)); // false + +console.log(isNegative(-0)); // true +console.log(isNegative(-1)); // true +console.log(isNegative(-Infinity)); // true +``` + +## `isNegativeZero` + +#### Signature + +```ts ignore +function isNegativeZero(it: N): it is NegativeZero; +``` + +Checks if a given value is negative zero, which is a special numeric value in +JavaScript, distinctly different from it's positive counterpart. Checking for +negative zero involves more than simply `x === -0`, as `-0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `-0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is negative zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero } from "jsr:@nick/is/number"; + +console.log(isNegativeZero(-0)); // true +console.log(isNegativeZero(0)); // false +console.log(isNegativeZero(-1)); // false +console.log(isNegativeZero(1)); // false +``` + +## `isNegativeZero` + +#### Signature + +```ts ignore +function isNegativeZero(it: unknown): it is NegativeZero; +``` + +Checks if a given value is negative zero, which is a special numeric value in +JavaScript, distinctly different from it's positive counterpart. Checking for +negative zero involves more than simply `x === -0`, as `-0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `-0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is negative zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero } from "jsr:@nick/is/number"; + +console.log(isNegativeZero(-0)); // true +console.log(isNegativeZero(0)); // false +console.log(isNegativeZero(-1)); // false +console.log(isNegativeZero(1)); // false +``` + +## `isNonZero` + +#### Signature + +```ts ignore +function isNonZero(it: N): it is NonZero; +``` + +Checks if a given value is a nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero } from "jsr:@nick/is/number/nonzero"; + +console.log(isNonZero(1)); // true +console.log(isNonZero(-1)); // true +console.log(isNonZero(1.5)); // true + +console.log(isNonZero(0)); // false +console.log(isNonZero(-0)); // false +console.log(isNonZero(NaN)); // false +console.log(isNonZero(Infinity)); // true +``` + +## `isNonZero` + +#### Signature + +```ts ignore +function isNonZero(it: unknown): it is NonZero; +``` + +Checks if a given value is a nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero } from "jsr:@nick/is/number/nonzero"; + +console.log(isNonZero(1)); // true +console.log(isNonZero(-1)); // true +console.log(isNonZero(1.5)); // true + +console.log(isNonZero(0)); // false +console.log(isNonZero(-0)); // false +console.log(isNonZero(NaN)); // false +console.log(isNonZero(Infinity)); // true +``` + +## `isNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isNonZeroFiniteInteger( + it: N, +): it is NonZeroFiniteInteger; +``` + +Checks if a given value is a nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteInteger(0)); // false +console.log(isNonZeroFiniteInteger(1)); // true +console.log(isNonZeroFiniteInteger(-1)); // true +console.log(isNonZeroFiniteInteger(1.5)); // false +console.log(isNonZeroFiniteInteger(NaN)); // false +console.log(isNonZeroFiniteInteger(Infinity)); // true +``` + +## `isNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isNonZeroFiniteInteger(it: unknown): it is NonZeroFiniteInteger; +``` + +Checks if a given value is a nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteInteger(0)); // false +console.log(isNonZeroFiniteInteger(1)); // true +console.log(isNonZeroFiniteInteger(-1)); // true +console.log(isNonZeroFiniteInteger(1.5)); // false +console.log(isNonZeroFiniteInteger(NaN)); // false +console.log(isNonZeroFiniteInteger(Infinity)); // true +``` + +## `isNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isNonZeroFiniteNumber(it: N): it is NonZeroFinite; +``` + +Checks if a given value is a nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteNumber(0)); // false +console.log(isNonZeroFiniteNumber(1)); // true +console.log(isNonZeroFiniteNumber(-1)); // true +console.log(isNonZeroFiniteNumber(1.5)); // true +console.log(isNonZeroFiniteNumber(NaN)); // false +console.log(isNonZeroFiniteNumber(Infinity)); // true +``` + +## `isNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isNonZeroFiniteNumber(it: unknown): it is NonZeroFinite; +``` + +Checks if a given value is a nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteNumber(0)); // false +console.log(isNonZeroFiniteNumber(1)); // true +console.log(isNonZeroFiniteNumber(-1)); // true +console.log(isNonZeroFiniteNumber(1.5)); // true +console.log(isNonZeroFiniteNumber(NaN)); // false +console.log(isNonZeroFiniteNumber(Infinity)); // true +``` + +## `isNonZeroInteger` + +#### Signature + +```ts ignore +function isNonZeroInteger(it: N): it is NonZeroInteger; +``` + +Checks if a given value is a nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroInteger(0)); // false +console.log(isNonZeroInteger(1)); // true +console.log(isNonZeroInteger(-1)); // true +console.log(isNonZeroInteger(1.5)); // false +console.log(isNonZeroInteger(NaN)); // false +console.log(isNonZeroInteger(Infinity)); // true +``` + +## `isNonZeroInteger` + +#### Signature + +```ts ignore +function isNonZeroInteger(it: unknown): it is NonZeroInteger; +``` + +Checks if a given value is a nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroInteger(0)); // false +console.log(isNonZeroInteger(1)); // true +console.log(isNonZeroInteger(-1)); // true +console.log(isNonZeroInteger(1.5)); // false +console.log(isNonZeroInteger(NaN)); // false +console.log(isNonZeroInteger(Infinity)); // true +``` + +## `isNonZeroNumber` + +#### Signature + +```ts ignore +function isNonZeroNumber(it: N): it is NonZero; +``` + +Checks if a given value is a nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero } from "jsr:@nick/is/number/nonzero"; + +console.log(isNonZero(1)); // true +console.log(isNonZero(-1)); // true +console.log(isNonZero(1.5)); // true + +console.log(isNonZero(0)); // false +console.log(isNonZero(-0)); // false +console.log(isNonZero(NaN)); // false +console.log(isNonZero(Infinity)); // true +``` + +## `isNonZeroNumber` + +#### Signature + +```ts ignore +function isNonZeroNumber(it: unknown): it is NonZero; +``` + +Checks if a given value is a nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero } from "jsr:@nick/is/number/nonzero"; + +console.log(isNonZero(1)); // true +console.log(isNonZero(-1)); // true +console.log(isNonZero(1.5)); // true + +console.log(isNonZero(0)); // false +console.log(isNonZero(-0)); // false +console.log(isNonZero(NaN)); // false +console.log(isNonZero(Infinity)); // true +``` + +## `isNumber` + +#### Signature + +```ts ignore +function isNumber(it: unknown): it is number; +``` + +Checks if the given value is a number. This includes all numbers, without +distinguishing between `NaN`, `Infinity`, and other special values. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a number, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isNumber } from "jsr:@nick/is/number"; + +isNumber("123"); // false +isNumber(123); // true +``` + +```ts +import { isNumber } from "jsr:@nick/is/number"; + +const x: unknown = 123; +if (isNumber(x)) { + console.log(x + 1); + // ^? const x: number +} +``` + +## `isOdd` + +#### Signature + +```ts ignore +function isOdd(it: T): it is Odd; +``` + +Checks if a given number / bigint is odd. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :----------------------------------------------------------------- | +| **`it`** | The number or bigint to check, either literal or in string format. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOdd` + +#### Signature + +```ts ignore +function isOdd(it: number | `${number}`): it is Odd; +``` + +Checks if a given number / numeric string is odd. Returns `true` if the value is +not divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------- | +| **`it`** | The number or numeric string to check. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOdd` + +#### Signature + +```ts ignore +function isOdd(it: bigint | `${bigint}`): it is Odd; +``` + +Checks if a given bigint or bigint string is an odd number. Returns `true` if +the value is not divisible by `2`, and `false` otherwise. This usually +corresponds to integers that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------ | +| **`it`** | The bigint or bigint string to check. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOdd` + +#### Signature + +```ts ignore +function isOdd(it: unknown): it is Odd; +``` + +Checks if a given number / bigint is odd. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an odd finite integer, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOddNumber` + +#### Signature + +```ts ignore +function isOddNumber(it: T): it is Odd; +``` + +Checks if a given number / bigint is odd. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :----------------------------------------------------------------- | +| **`it`** | The number or bigint to check, either literal or in string format. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOddNumber` + +#### Signature + +```ts ignore +function isOddNumber(it: number | `${number}`): it is Odd; +``` + +Checks if a given number / numeric string is odd. Returns `true` if the value is +not divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------- | +| **`it`** | The number or numeric string to check. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOddNumber` + +#### Signature + +```ts ignore +function isOddNumber(it: bigint | `${bigint}`): it is Odd; +``` + +Checks if a given bigint or bigint string is an odd number. Returns `true` if +the value is not divisible by `2`, and `false` otherwise. This usually +corresponds to integers that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------ | +| **`it`** | The bigint or bigint string to check. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOddNumber` + +#### Signature + +```ts ignore +function isOddNumber(it: unknown): it is Odd; +``` + +Checks if a given number / bigint is odd. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an odd finite integer, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isPositive` + +#### Signature + +```ts ignore +function isPositive(it: N): it is Positive; +``` + +Checks if a given value is a positive number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive } from "jsr:@nick/is/integer"; + +console.log(isPositive(0)); // true +console.log(isPositive(1)); // true +console.log(isPositive(-1)); // false +console.log(isPositive(1.5)); // true +console.log(isPositive(NaN)); // false +console.log(isPositive(Infinity)); // true +``` + +## `isPositive` + +#### Signature + +```ts ignore +function isPositive(it: unknown): it is Positive; +``` + +Checks if a given value is a positive number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive } from "jsr:@nick/is/integer"; + +console.log(isPositive(0)); // true +console.log(isPositive(1)); // true +console.log(isPositive(-1)); // false +console.log(isPositive(1.5)); // true +console.log(isPositive(NaN)); // false +console.log(isPositive(Infinity)); // true +``` + +## `isPositiveFiniteInteger` + +#### Signature + +```ts ignore +function isPositiveFiniteInteger( + it: N, +): it is PositiveFiniteInteger; +``` + +Checks if a given value is a positive finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteInteger(0)); // false +console.log(isPositiveFiniteInteger(1)); // true +console.log(isPositiveFiniteInteger(-1)); // false +console.log(isPositiveFiniteInteger(1.5)); // false +console.log(isPositiveFiniteInteger(NaN)); // false +console.log(isPositiveFiniteInteger(Infinity)); // false +``` + +## `isPositiveFiniteInteger` + +#### Signature + +```ts ignore +function isPositiveFiniteInteger(it: unknown): it is PositiveFiniteInteger; +``` + +Checks if a given value is a positive finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteInteger(0)); // false +console.log(isPositiveFiniteInteger(1)); // true +console.log(isPositiveFiniteInteger(-1)); // false +console.log(isPositiveFiniteInteger(1.5)); // false +console.log(isPositiveFiniteInteger(NaN)); // false +console.log(isPositiveFiniteInteger(Infinity)); // false +``` + +## `isPositiveFiniteNumber` + +#### Signature + +```ts ignore +function isPositiveFiniteNumber(it: N): it is PositiveFinite; +``` + +Checks if a given value is a positive finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteNumber(0)); // false +console.log(isPositiveFiniteNumber(1)); // true +console.log(isPositiveFiniteNumber(-1)); // false +console.log(isPositiveFiniteNumber(1.5)); // true +console.log(isPositiveFiniteNumber(NaN)); // false +console.log(isPositiveFiniteNumber(Infinity)); // false +``` + +## `isPositiveFiniteNumber` + +#### Signature + +```ts ignore +function isPositiveFiniteNumber(it: unknown): it is PositiveFinite; +``` + +Checks if a given value is a positive finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteNumber(0)); // false +console.log(isPositiveFiniteNumber(1)); // true +console.log(isPositiveFiniteNumber(-1)); // false +console.log(isPositiveFiniteNumber(1.5)); // true +console.log(isPositiveFiniteNumber(NaN)); // false +console.log(isPositiveFiniteNumber(Infinity)); // false +``` + +## `isPositiveInfinity` + +#### Signature + +```ts ignore +function isPositiveInfinity(it: unknown): it is PositiveInfinity; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is positive infinity, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `positive` `infinity` + +#### Examples + +```ts +import { isPositiveInfinity } from "@nick/is/number/infinity"; + +console.log(isPositiveInfinity(Infinity)); // false +console.log(isPositiveInfinity(-Infinity)); // true +console.log(isPositiveInfinity(1)); // false +console.log(isPositiveInfinity(-1)); // false +console.log(isPositiveInfinity(NaN)); // false +``` + +## `isPositiveInteger` + +#### Signature + +```ts ignore +function isPositiveInteger(it: N): it is PositiveInteger; +``` + +Checks if a given value is a positive integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveInteger(0)); // true +console.log(isPositiveInteger(1)); // true +console.log(isPositiveInteger(-1)); // false +console.log(isPositiveInteger(1.5)); // false +console.log(isPositiveInteger(NaN)); // false +console.log(isPositiveInteger(Infinity)); // false +``` + +## `isPositiveInteger` + +#### Signature + +```ts ignore +function isPositiveInteger(it: unknown): it is PositiveInteger; +``` + +Checks if a given value is a positive integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveInteger(0)); // true +console.log(isPositiveInteger(1)); // true +console.log(isPositiveInteger(-1)); // false +console.log(isPositiveInteger(1.5)); // false +console.log(isPositiveInteger(NaN)); // false +console.log(isPositiveInteger(Infinity)); // false +``` + +## `isPositiveNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isPositiveNonZeroFiniteInteger( + it: N, +): it is PositiveNonZeroFiniteInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteInteger(0)); // false +console.log(isPositiveNonZeroFiniteInteger(1)); // true +console.log(isPositiveNonZeroFiniteInteger(-1)); // false +console.log(isPositiveNonZeroFiniteInteger(1.5)); // false +console.log(isPositiveNonZeroFiniteInteger(NaN)); // false +console.log(isPositiveNonZeroFiniteInteger(Infinity)); // true +``` + +## `isPositiveNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isPositiveNonZeroFiniteInteger( + it: unknown, +): it is PositiveNonZeroFiniteInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteInteger(0)); // false +console.log(isPositiveNonZeroFiniteInteger(1)); // true +console.log(isPositiveNonZeroFiniteInteger(-1)); // false +console.log(isPositiveNonZeroFiniteInteger(1.5)); // false +console.log(isPositiveNonZeroFiniteInteger(NaN)); // false +console.log(isPositiveNonZeroFiniteInteger(Infinity)); // true +``` + +## `isPositiveNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroFiniteNumber( + it: N, +): it is PositiveNonZeroFinite; +``` + +Checks if a given value is a positive nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteNumber(0)); // false +console.log(isPositiveNonZeroFiniteNumber(1)); // true +console.log(isPositiveNonZeroFiniteNumber(-1)); // false +console.log(isPositiveNonZeroFiniteNumber(1.5)); // true +console.log(isPositiveNonZeroFiniteNumber(NaN)); // false +console.log(isPositiveNonZeroFiniteNumber(Infinity)); // true +``` + +## `isPositiveNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroFiniteNumber( + it: unknown, +): it is PositiveNonZeroFinite; +``` + +Checks if a given value is a positive nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteNumber(0)); // false +console.log(isPositiveNonZeroFiniteNumber(1)); // true +console.log(isPositiveNonZeroFiniteNumber(-1)); // false +console.log(isPositiveNonZeroFiniteNumber(1.5)); // true +console.log(isPositiveNonZeroFiniteNumber(NaN)); // false +console.log(isPositiveNonZeroFiniteNumber(Infinity)); // true +``` + +## `isPositiveNonZeroInteger` + +#### Signature + +```ts ignore +function isPositiveNonZeroInteger( + it: N, +): it is PositiveNonZeroInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroInteger(0)); // false +console.log(isPositiveNonZeroInteger(1)); // true +console.log(isPositiveNonZeroInteger(-1)); // false +console.log(isPositiveNonZeroInteger(1.5)); // false +console.log(isPositiveNonZeroInteger(NaN)); // false +console.log(isPositiveNonZeroInteger(Infinity)); // true +``` + +## `isPositiveNonZeroInteger` + +#### Signature + +```ts ignore +function isPositiveNonZeroInteger(it: unknown): it is PositiveNonZeroInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroInteger(0)); // false +console.log(isPositiveNonZeroInteger(1)); // true +console.log(isPositiveNonZeroInteger(-1)); // false +console.log(isPositiveNonZeroInteger(1.5)); // false +console.log(isPositiveNonZeroInteger(NaN)); // false +console.log(isPositiveNonZeroInteger(Infinity)); // true +``` + +## `isPositiveNonZeroNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroNumber(it: N): it is PositiveNonZero; +``` + +Checks if a given value is a positive nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroNumber(0)); // false +console.log(isPositiveNonZeroNumber(1)); // true +console.log(isPositiveNonZeroNumber(-1)); // false +console.log(isPositiveNonZeroNumber(1.5)); // true +console.log(isPositiveNonZeroNumber(NaN)); // false +console.log(isPositiveNonZeroNumber(Infinity)); // true +``` + +## `isPositiveNonZeroNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroNumber(it: unknown): it is PositiveNonZero; +``` + +Checks if a given value is a positive nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroNumber(0)); // false +console.log(isPositiveNonZeroNumber(1)); // true +console.log(isPositiveNonZeroNumber(-1)); // false +console.log(isPositiveNonZeroNumber(1.5)); // true +console.log(isPositiveNonZeroNumber(NaN)); // false +console.log(isPositiveNonZeroNumber(Infinity)); // true +``` + +## `isPositiveNonZeroNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroNumber(it: unknown): it is PositiveNonZero; +``` + +## `isPositiveNumber` + +#### Signature + +```ts ignore +function isPositiveNumber(it: N): it is Positive; +``` + +Checks if a given value is a positive number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive } from "jsr:@nick/is/integer"; + +console.log(isPositive(0)); // true +console.log(isPositive(1)); // true +console.log(isPositive(-1)); // false +console.log(isPositive(1.5)); // true +console.log(isPositive(NaN)); // false +console.log(isPositive(Infinity)); // true +``` + +## `isPositiveNumber` + +#### Signature + +```ts ignore +function isPositiveNumber(it: unknown): it is Positive; +``` + +Checks if a given value is a positive number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive } from "jsr:@nick/is/integer"; + +console.log(isPositive(0)); // true +console.log(isPositive(1)); // true +console.log(isPositive(-1)); // false +console.log(isPositive(1.5)); // true +console.log(isPositive(NaN)); // false +console.log(isPositive(Infinity)); // true +``` + +## `isPositiveZero` + +#### Signature + +```ts ignore +function isPositiveZero(it: N): it is PositiveZero; +``` + +Checks if a given value is positive zero, which is a special numeric value in +JavaScript, distinctly different from it's negative counterpart. Checking for +positive zero involves more than simply `x === +0`, as `+0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `+0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is positive zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero } from "jsr:@nick/is/number"; + +console.log(isPositiveZero(-0)); // false +console.log(isPositiveZero(0)); // true +console.log(isPositiveZero(-1)); // false +console.log(isPositiveZero(1)); // false +``` + +## `isPositiveZero` + +#### Signature + +```ts ignore +function isPositiveZero(it: unknown): it is PositiveZero; +``` + +Checks if a given value is positive zero, which is a special numeric value in +JavaScript, distinctly different from it's negative counterpart. Checking for +positive zero involves more than simply `x === +0`, as `+0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `+0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is positive zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero } from "jsr:@nick/is/number"; + +console.log(isPositiveZero(-0)); // false +console.log(isPositiveZero(0)); // true +console.log(isPositiveZero(-1)); // false +console.log(isPositiveZero(1)); // false +``` + +## `isUint16` + +#### Signature + +```ts ignore +function isUint16(it: N): it is Uint16; +``` + +Checks if a given value is an unsigned 16-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `isUint16` + +#### Signature + +```ts ignore +function isUint16(it: unknown): it is Uint16; +``` + +Checks if a given value is an unsigned 16-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `isUint32` + +#### Signature + +```ts ignore +function isUint32(it: N): it is Uint32; +``` + +Checks if a given value is an unsigned 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `isUint32` + +#### Signature + +```ts ignore +function isUint32(it: unknown): it is Uint32; +``` + +Checks if a given value is an unsigned 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `isUint8` + +#### Signature + +```ts ignore +function isUint8(it: N): it is Uint8; +``` + +Checks if a given value is an unsigned 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint8 } from "jsr:@nick/is/uint8"; + +isUint8(1); // true +isUint8(128); // true +isUint8(0xFF); // true +isUint8(-1); // false +isUint8(420); // false +``` + +## `isUint8` + +#### Signature + +```ts ignore +function isUint8(it: unknown): it is Uint8; +``` + +Checks if a given value is an unsigned 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint8 } from "jsr:@nick/is/uint8"; + +isUint8(1); // true +isUint8(128); // true +isUint8(0xFF); // true +isUint8(-1); // false +isUint8(420); // false +``` + +## `isZero` + +#### Signature + +```ts ignore +function isZero(it: N): it is Zero; +``` + +Checks if a given value is a zero number. This includes both positive and +negative zero. It also supports numbers and numeric strings. + +- To check exclusively for `-0`, use + [isNegativeZero](#isnegativezero "Jump to symbol: 'isNegativeZero'") instead. +- To check exclusively for `+0` (meaning zero, but **not** negative zero), use + [isPositiveZero](#ispositivezero "Jump to symbol: 'isPositiveZero'") instead. + +###### Category + +`Numbers` + +## `isZero` + +#### Signature + +```ts ignore +function isZero(it: unknown): it is Zero; +``` + +Checks if a given value is a zero number. This includes both positive and +negative zero. It also supports numbers and numeric strings. + +- To check exclusively for `-0`, use + [isNegativeZero](#isnegativezero "Jump to symbol: 'isNegativeZero'") instead. +- To check exclusively for `+0` (meaning zero, but **not** negative zero), use + [isPositiveZero](#ispositivezero "Jump to symbol: 'isPositiveZero'") instead. + +###### Category + +`Numbers` + +## `AnyRange` + +#### Signature + +```ts ignore +export type AnyRange = + | RangeInclusiveMin + | RangeInclusive + | RangeInclusiveMax + | RangeExclusive; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `BigInteger` + +#### Signature + +```ts ignore +export type BigInteger = CastInt; +``` + +Casts a value into a big integer type (which is really just a bigint). If the +value is not a bigint or a string containing a valid integer, it will resolve to +`never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `Cast` + +#### Signature + +```ts ignore +export type Cast = Extract & T; +``` + +Casts a value into a specific numeric type. If the value is not a number, it +will resolve to `never`, indicating its incompatibility with the type. + +This is a low-level utility type that primarily serves as an internal helper for +more user-friendly types like [Integer](#integer "Jump to symbol: 'Integer'") +and [Positive](#positive "Jump to symbol: 'Positive'"). Unless you're building +custom numeric types with your own branding, you most likely never directly +handle this type in the wild. + +##### Type Parameters + +- **`N`** +- **`T`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { Cast } from "jsr:@nick/is/number"; + +declare const MY_DOUBLE: unique symbol; +type DOUBLE = Cast; + +let x = 4.3210123210 as DOUBLE; +let y = 3.1415926535 as DOUBLE; + +console.log(x + y); // 7.4626049745 + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'DOUBLE'. +``` + +## `CastInt` + +#### Signature + +```ts ignore +export type CastInt = Extract & T; +``` + +Casts a value into a specific integer type. If the value is not a bigint, it +will resolve to `never`, indicating its incompatibility with the type. + +This is a low-level utility type that primarily serves as an internal helper for +more user-friendly types like +[BigInteger](#biginteger "Jump to symbol: 'BigInteger'") or +[PositiveBigInteger](#positivebiginteger "Jump to symbol: 'PositiveBigInteger'"). +Unless you're building custom numeric types with your own branding, you most +likely will never directly handle this type in the wild. + +##### Type Parameters + +- **`N`** +- **`T`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { CastInt } from "jsr:@nick/is/number"; + +declare const INTEGER: unique symbol; +type INTEGER = CastInt; + +let x = 3n as INTEGER; +let y = 5n as INTEGER; + +console.log(x + y); // 8n +``` + +## `Derange` + +#### Signature + +```ts ignore +export type Derange = + | readonly [number, number, "[]"] + | readonly [number, "[]"] + | readonly [number, number, "[)"] + | readonly [number, "[)"] + | readonly [number, number, "(]"] + | readonly [number, "(]"] + | readonly [number, number, "()"] + | readonly [number, "()"] + | readonly [number, number, Exclusivity] + | readonly [number, Exclusivity]; +``` + +## `Even` + +#### Signature + +```ts ignore +export type Even = Cast; +``` + +Branded type representing an even number or bigint. Used by overloads of the +[`isEven`](#iseven "Jump to symbol: 'isEven'") function to differentiate between +odd and even numbers. + +##### Type Parameters + +- **`T`** extends `Numeric` (default: `Numeric`) + +--- + +###### Category + +`Numeric` + +## `Exclusivity` + +#### Signature + +```ts ignore +export type Exclusivity = AnyRange[2]; +``` + +## `Finite` + +#### Signature + +```ts ignore +export type Finite = Cast; +``` + +Casts a value into a finite type. If the value is not a number, it will resolve +to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `FiniteInteger` + +#### Signature + +```ts ignore +export type FiniteInteger = Cast; +``` + +Casts a value into a finite integer type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `Float` + +#### Signature + +```ts ignore +export type Float = Cast; +``` + +Casts a value into a floating-point type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float` `number` + +#### Examples + +```ts +import { type Float, isFloat } from "@nick/is/float"; + +let x = 1.5 as Float, y = 0; + +if (isFloat(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float'. +``` + +## `Float16` + +#### Signature + +```ts ignore +export type Float16 = Cast; +``` + +Casts a value into a 16-bit floating-point type (half-precision). + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float16` `number` + +#### Examples + +```ts +import { type Float16, isFloat16 } from "@nick/is/float16"; + +let i = 1.5 as Float16, y = 0; + +if (isFloat16(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = 1; // <- TS2322 Type '1' is not assignable to type 'Float16'. +``` + +## `Float32` + +#### Signature + +```ts ignore +export type Float32 = Cast; +``` + +Casts a value into a floating-point type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float32` `number` + +#### Examples + +```ts +import { type Float32, isFloat32 } from "@nick/is/float32"; + +let x = 1.5 as Float32, y = 0; + +if (isFloat32(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float32'. +``` + +## `Float64` + +#### Signature + +```ts ignore +export type Float64 = Cast; +``` + +Casts a value into a float64-precision floating-point type. If the value is not +a number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float64` `number` + +#### Examples + +```ts +import { type Float64, isFloat64 } from "jsr:@type/number/float64"; + +let x = 1.5 as Float64, y = 0; + +if (isFloat64(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float64'. +``` + +## `Infinity` + +#### Signature + +```ts ignore +export type Infinity = PositiveInfinity | NegativeInfinity; +``` + +Special type representing either positive or negative infinity. + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` + +## `InRange` + +#### Signature + +```ts ignore +export type InRange< + N extends number, + Min extends number = number, + Max extends number = number, + Tex extends Exclusivity = Exclusivity, +> = + & (number extends N ? IsInRange + : `${Min}|${Max}` extends `-${number}|-${number}` + ? `${N}` extends `-${number}` ? IsInRange : never + : `${Min}|${Max}` extends `${number}|-${number}` ? never + : `${Min}|${Max}` extends `-${number}|${number}` + ? `${N}` extends `-${number}` ? IsInRange : never + : `${N}` extends `-${number}` ? never + : IsInRange) + & N; +``` + +Type-level equivalent to the [`inRange`](#inrange "Jump to symbol: 'inRange'") +function, which (naively) checks if a number is within a given range. The range +can be specified in multiple ways, with one of four different exclusivity types. + +##### Type Parameters + +- **`N`** extends `number` +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `Exclusivity`) + +--- + +###### See Also + +- [`inRange`](#inrange "Jump to symbol: 'inRange'") for more information. + +## `Int16` + +#### Signature + +```ts ignore +export type Int16 = Cast; +``` + +Casts a value into a signed 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/int16"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -32769; // <- TS2322 Type '-32769' is not assignable to type 'Int16'. +``` + +## `Int32` + +#### Signature + +```ts ignore +export type Int32 = Cast; +``` + +Casts a value into a signed 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int32` `number` + +#### Examples + +```ts +import { type Int32, isInt32 } from "jsr:@type/number/int32"; + +let value = 1 as Int32; + +const setValue = (newValue: Int32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -2147483649; // <- TS2322 Type '-2147483649' is not assignable to type 'Int32'. +``` + +## `Int8` + +#### Signature + +```ts ignore +export type Int8 = Cast; +``` + +Casts a value into a signed 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int8` `number` + +#### Examples + +```ts +import { type Int8, isInt8 } from "@nick/is/int8"; + +let i = 1 as Int8, y = 0; + +if (isInt8(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = 1.5; // <- TS2322 Type '1.5' is not assignable to type 'Int8'. +``` + +## `Integer` + +#### Signature + +```ts ignore +export type Integer = N extends bigint + ? `${N}` extends `${infer I extends number}` ? N & Integer : never + : N extends number + ? number extends N ? N & INTEGER + : `${N}` extends `${bigint}` ? N & INTEGER : never + : never; +``` + +Casts a value into an integer type. If the value is not an number, or is a +non-integral number like 3.14, it will resolve to `never`. + +**Note**: once a value is cast to a type with this narrow of a constraint, +TypeScript's compiler will refuse any assignment to it that is not _exactly_ +compatible with the type. If you find yourself encountering errors about +incompatible types, try using the +[MaybeInteger](#maybeinteger "Jump to symbol: 'MaybeInteger'") type instead. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { type Integer, isInteger } from "jsr:@type/number"; + +function add(a: Integer, b: Integer) { + return (a + b) as Integer; +} + +let x = 1 as Integer, y = 2 as Integer, z = 3; + +if (isInteger(z)) { + console.log(add(add(x, y), z)); +} else { + console.log(add(x, y)); +} + +// These will raise TypeScript compiler errors: +add(x, z); +add(y, 3); + +// This level of strictness can be a bit silly in the wrong application: +x = 1; // <- TS4321 (`MaybeInteger` would be a better choice here) +``` + +## `IsEven` + +#### Signature + +```ts ignore +export type IsEven = `${T}` extends + `${"" | bigint}${1 | 3 | 5 | 7 | 9}` ? True : False; +``` + +Type-level equivalent of [`isEven`](#iseven "Jump to symbol: 'isEven'"), which +checks if a given numeric type (number or bigint) ends in an even number. +Returns [True](#true "Jump to symbol: 'True'") if so, and +[False](#false "Jump to symbol: 'False'") otherwise. + +##### Type Parameters + +- **`T`** extends `Numeric` +- **`True`** (default: `T`) +- **`False`** (default: `never`) + +--- + +###### Category + +`Numeric` + +## `IsOdd` + +#### Signature + +```ts ignore +export type IsOdd = + `${number}` extends `${T}` ? True + : `${bigint}` extends `${T}` ? True + : `${T}` extends `${infer _}${1 | 3 | 5 | 7 | 9}` ? True + : False; +``` + +Type-level equivalent of [`isOdd`](#isodd "Jump to symbol: 'isOdd'"), which +checks if a given numeric type (number or bigint) ends in an odd number. Returns +[True](#true "Jump to symbol: 'True'") if so, and +[False](#false "Jump to symbol: 'False'") otherwise. + +##### Type Parameters + +- **`T`** extends `Numeric` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Numeric` + +## `MaybeFinite` + +#### Signature + +```ts ignore +export type MaybeFinite = Cast; +``` + +Casts a value into a partial finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeFloat` + +#### Signature + +```ts ignore +export type MaybeFloat = Cast; +``` + +Casts a value into a partial floating-point type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float` `number` + +#### Examples + +```ts +import { isFloat, type MaybeFloat } from "@nick/is/float"; + +let x = 1.5 as MaybeFloat, y = 0; + +if (isFloat(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Float`) +``` + +## `MaybeFloat16` + +#### Signature + +```ts ignore +export type MaybeFloat16 = Cast; +``` + +Casts a value into a partial 16-bit floating-point type (half-precision). + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float16` `number` + +## `MaybeFloat32` + +#### Signature + +```ts ignore +export type MaybeFloat32 = Cast; +``` + +Casts a value into a partial floating-point type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float32` `number` + +#### Examples + +```ts +import { isFloat32, type MaybeFloat32 } from "@nick/is/float32"; + +let x = 1.5 as MaybeFloat32, y = 0; + +if (isFloat32(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Float32`) +``` + +## `MaybeFloat64` + +#### Signature + +```ts ignore +export type MaybeFloat64 = Cast; +``` + +Casts a value into a partial float64-precision floating-point type. If the value +is not a number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float64` `number` + +#### Examples + +```ts +import { isFloat64, type MaybeFloat64 } from "jsr:@type/number/float64"; + +let x = 1.5 as MaybeFloat64, y = 0; + +if (isFloat64(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Float64`) +``` + +## `MaybeInt16` + +#### Signature + +```ts ignore +export type MaybeInt16 = Cast; +``` + +Casts a value into a partial signed 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/int16"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +value = -32769; // Error: Type '-32769' is not assignable to type 'Int16'. +``` + +## `MaybeInt32` + +#### Signature + +```ts ignore +export type MaybeInt32 = Cast; +``` + +Casts a value into a partial signed 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int32` `number` + +#### Examples + +```ts +import { isInt32, type MaybeInt32 } from "jsr:@type/number/int32"; + +let value = 1 as MaybeInt32; + +const setValue = (newValue: MaybeInt32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! +value = -2147483649; // <- No error! (this is the main difference from `Int32`) +``` + +## `MaybeInt8` + +#### Signature + +```ts ignore +export type MaybeInt8 = Cast; +``` + +Casts a value into a partial signed 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int8` `number` + +#### Examples + +```ts +import { isInt8, type MaybeInt8 } from "@nick/is/int8"; + +let i = 1 as MaybeInt8, y = 0; + +if (isInt8(i)) { + console.log(i); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Int8`) +``` + +## `MaybeInteger` + +#### Signature + +```ts ignore +export type MaybeInteger = N extends bigint + ? `${N}` extends `${infer I extends number}` ? N & MaybeInteger : never + : N extends number + ? number extends N ? N & MAYBE_INTEGER + : `${N}` extends `${bigint}` ? N & MAYBE_INTEGER + : never + : never; +``` + +Casts a value into a partial integer type. If the value is not an number, or is +a non-integral number like 3.14, it will resolve to `never`. This type is nearly +identical to [Integer](#integer "Jump to symbol: 'Integer'"), except it allows +assignment of values that are not precisely compatible with the type, while +still providing an extra level of type safety over the base `number` type. + +Once a value is cast to a type of this constraint, TypeScript's compiler will +refuse any incompatible assignment to it. To demonstrate, consider this example: + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { + isInteger, + type MaybeFloat, + type MaybeInteger, +} from "jsr:@type/number"; + +function add(a: MaybeInteger, b: MaybeInteger) { + return (a + b) as MaybeInteger; +} + +let x = 1 as MaybeInteger, y = 2 as MaybeInteger, z = 3; +let xx = 1.1 as MaybeFloat, yy = 2.2 as MaybeFloat, zz = 3.3; + +if (isInteger(z)) { + console.log(add(add(x, y), z)); +} else { + console.log(add(x, y)); +} + +// These will raise TypeScript compiler errors: +add(x, yy); // <- TS2345 Type 'MaybeFloat' is not assignable to type 'MaybeInteger'. +y = yy; // <- TS2322 Type 'MaybeFloat' is not assignable to type 'MaybeInteger'. + +y = 2; // <- No error! (this is the main difference from `Integer`) +``` + +## `MaybeNaN` + +#### Signature + +```ts ignore +export type MaybeNaN = Cast; +``` + +Casts a value into a partial `NaN` type. This is a more forgiving form of the +[`NaN`](#nan "Jump to symbol: 'NaN'") type, which allows for the assignment of +other numeric values, but still retains the ability to distinguish itself from +generic numbers. This is often called a "Flavored" type, whereas the stricter +[`NaN`](#nan "Jump to symbol: 'NaN'") is known as a "Branded" type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNaN, type MaybeNaN } from "jsr:@type/number"; + +let x = NaN as MaybeNaN, y = 0; + +if (isNaN(x)) { + console.log(x); +} else { + console.log(y); +} + +y = NaN; // <- No error! (this is the main difference from `NaN`) +``` + +## `MaybeNegative` + +#### Signature + +```ts ignore +export type MaybeNegative = Cast; +``` + +Casts a value into a partial negative type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Types` `Numbers` + +###### Tags + +`maybe` `negative` `number` + +#### Examples + +```ts +import { isNegative, type MaybeNegative } from "jsr:@type/number"; + +let x = -1 as MaybeNegative, y = 0; + +if (isNegative(x)) { + console.log(x); +} else { + console.log(y); +} + +y = -1; // <- No error! (this is the main difference from `Negative`) +``` + +## `MaybeNegativeFinite` + +#### Signature + +```ts ignore +export type MaybeNegativeFinite = Cast; +``` + +Casts a value into a partial negative finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeNegativeNonZero` + +#### Signature + +```ts ignore +export type MaybeNegativeNonZero = Cast< + N, + MAYBE_NEGATIVE & MAYBE_NON_ZERO +>; +``` + +Casts a value into a partial negative nonzero type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeNegativeNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybeNegativeNonZeroFinite = Cast< + N, + MAYBE_NEGATIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a partial negative nonzero finite type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeNegativeZero` + +#### Signature + +```ts ignore +export type MaybeNegativeZero = Cast; +``` + +Casts a value into a partial negative zero type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero, type MaybeNegativeZero } from "jsr:@type/number"; + +let x = -0 as MaybeNegativeZero, y = 0; + +if (isNegativeZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = -0; // <- No error! (this is the main difference from `NegativeZero`) +``` + +## `MaybeNonZero` + +#### Signature + +```ts ignore +export type MaybeNonZero = Cast; +``` + +Casts a value into a partial nonzero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero, type MaybeNonZero } from "jsr:@type/number"; + +let x = 1 as MaybeNonZero, y = 0; + +if (isNonZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `NonZero`) +``` + +## `MaybeNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybeNonZeroFinite = Cast; +``` + +Casts a value into a partial nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +## `MaybePositive` + +#### Signature + +```ts ignore +export type MaybePositive = Cast; +``` + +Casts a value into a partial positive type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `positive` `number` + +#### Examples + +```ts +import { isPositive, type MaybePositive } from "jsr:@type/number"; + +let x = 1 as MaybePositive, y = 0; + +if (isPositive(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Positive`) +``` + +## `MaybePositiveFinite` + +#### Signature + +```ts ignore +export type MaybePositiveFinite = Cast; +``` + +Casts a value into a partial positive finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybePositiveNonZero` + +#### Signature + +```ts ignore +export type MaybePositiveNonZero = Cast< + N, + MAYBE_POSITIVE & MAYBE_NON_ZERO +>; +``` + +Casts a value into a partial positive nonzero type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybePositiveNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybePositiveNonZeroFinite = Cast< + N, + MAYBE_POSITIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a partial positive nonzero finite type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybePositiveZero` + +#### Signature + +```ts ignore +export type MaybePositiveZero = Cast; +``` + +Casts a value into a partial positive zero type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero, type MaybePositiveZero } from "jsr:@type/number"; + +let x = 0 as MaybePositiveZero, y = 1; + +if (isPositiveZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 0; // <- No error! (this is the main difference from `PositiveZero`) +``` + +## `MaybeUint16` + +#### Signature + +```ts ignore +export type MaybeUint16 = Cast; +``` + +Casts a value into a partial unsigned 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `MaybeUint32` + +#### Signature + +```ts ignore +export type MaybeUint32 = Cast; +``` + +Casts a value into a partial unsigned 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `MaybeUint8` + +#### Signature + +```ts ignore +export type MaybeUint8 = Cast; +``` + +Casts a value into a partial unsigned 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint8, type MaybeUint8 } from "@nick/is/uint8"; + +let i = 1 as MaybeUint8, y = 0; + +if (isUint8(i)) { + console.log(i); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Uint8`) +``` + +## `MaybeZero` + +#### Signature + +```ts ignore +export type MaybeZero = Cast; +``` + +Casts a value into a partial zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isZero, type MaybeZero } from "jsr:@type/number"; + +let x = 0 as MaybeZero, y = 1; + +if (isZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 0; // <- No error! (this is the main difference from `Zero`) +``` + +## `NaN` + +#### Signature + +```ts ignore +export type NaN = Cast; +``` + +Casts a value into a branded type that represents the special numeric value +`NaN` (not a number). This is a very strict type, and it prevents any other type +from being assigned unless they pass the +[`isNaN`](#isnan "Jump to symbol: 'isNaN'") type guard. If the value is not a +subtype of `number`, this will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNan, type NaN } from "jsr:@type/number"; + +let x = NaN as NaN, y = 0; + +if (isNan(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NaN'. +``` + +## `Negative` + +#### Signature + +```ts ignore +export type Negative = Cast; +``` + +Casts a value into a negative type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`negative` `number` + +#### Examples + +```ts +import { isNegative, type Negative } from "jsr:@type/number"; + +let x = -1 as Negative, y = 0; + +if (isNegative(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'Negative'. +``` + +## `NegativeBigInteger` + +#### Signature + +```ts ignore +export type NegativeBigInteger = CastInt; +``` + +Casts a value into a negative big integer type. If the value is not a bigint or +a string containing a valid integer, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `NegativeFinite` + +#### Signature + +```ts ignore +export type NegativeFinite = Cast; +``` + +Casts a value into a negative finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeFiniteInteger` + +#### Signature + +```ts ignore +export type NegativeFiniteInteger = Cast< + N, + NEGATIVE & FINITE & INTEGER +>; +``` + +Casts a value into a negative finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeInfinity` + +#### Signature + +```ts ignore +export type NegativeInfinity = -Infinity; +``` + +Special type representing negative infinity (`Number.NEGATIVE_INFINITY`). + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` `negative` + +## `NegativeInteger` + +#### Signature + +```ts ignore +export type NegativeInteger = Cast; +``` + +Casts a value into a negative integer type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZero` + +#### Signature + +```ts ignore +export type NegativeNonZero = Cast; +``` + +Casts a value into a negative nonzero type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZeroFinite` + +#### Signature + +```ts ignore +export type NegativeNonZeroFinite = Cast< + N, + NEGATIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a negative nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type NegativeNonZeroFiniteInteger = Cast< + N, + NEGATIVE & NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a negative nonzero finite integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZeroInteger` + +#### Signature + +```ts ignore +export type NegativeNonZeroInteger = Cast< + N, + NEGATIVE & NON_ZERO & INTEGER +>; +``` + +Casts a value into a negative nonzero integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeZero` + +#### Signature + +```ts ignore +export type NegativeZero = Cast; +``` + +Casts a value into a negative zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero, type NegativeZero } from "jsr:@type/number"; + +let x = -0 as NegativeZero, y = 0; + +if (isNegativeZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NegativeZero'. +``` + +## `NonZero` + +#### Signature + +```ts ignore +export type NonZero = Cast; +``` + +Casts a value into a nonzero type. If the value is not a number, it will resolve +to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero, type NonZero } from "jsr:@type/number"; + +let x = 1 as NonZero, y = 0; + +if (isNonZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NonZero'. +``` + +## `NonZeroFinite` + +#### Signature + +```ts ignore +export type NonZeroFinite = Cast; +``` + +Casts a value into a nonzero finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type NonZeroFiniteInteger = Cast< + N, + NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a nonzero finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NonZeroInteger` + +#### Signature + +```ts ignore +export type NonZeroInteger = Cast; +``` + +Casts a value into a nonzero integer type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `Numeric` + +#### Signature + +```ts ignore +export type Numeric = number | bigint | `${number | bigint}`; +``` + +## `Odd` + +#### Signature + +```ts ignore +export type Odd = Cast< + IsOdd, Extract, never>, + ODD +>; +``` + +Branded type representing an odd number. Used by overloads of the +[`isOdd`](#isodd "Jump to symbol: 'isOdd'") function to differentiate between +odd and even numbers. + +##### Type Parameters + +- **`T`** (default: `number`) + +--- + +###### Category + +`Numeric` + +## `Positive` + +#### Signature + +```ts ignore +export type Positive = Cast; +``` + +Casts a value into a positive type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive, type Positive } from "jsr:@type/number"; + +let x = 1 as Positive, y = 0; + +if (isPositive(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'Positive'. +``` + +## `PositiveBigInteger` + +#### Signature + +```ts ignore +export type PositiveBigInteger = CastInt; +``` + +Casts a value into a positive big integer type. If the value is not a bigint or +a string containing a valid integer, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `PositiveFinite` + +#### Signature + +```ts ignore +export type PositiveFinite = Cast; +``` + +Casts a value into a positive finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveFiniteInteger` + +#### Signature + +```ts ignore +export type PositiveFiniteInteger = Cast< + N, + POSITIVE & FINITE & INTEGER +>; +``` + +Casts a value into a positive finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveInfinity` + +#### Signature + +```ts ignore +export type PositiveInfinity = Infinity; +``` + +Special type representing positive infinity (`Number.POSITIVE_INFINITY`). + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` `positive` + +## `PositiveInteger` + +#### Signature + +```ts ignore +export type PositiveInteger = Cast; +``` + +Casts a value into a positive finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZero` + +#### Signature + +```ts ignore +export type PositiveNonZero = Cast; +``` + +Casts a value into a positive nonzero type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZeroFinite` + +#### Signature + +```ts ignore +export type PositiveNonZeroFinite = Cast< + N, + POSITIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a positive nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type PositiveNonZeroFiniteInteger = Cast< + N, + POSITIVE & NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a positive nonzero finite integer type. If the value is not a +number, it will resolve to `never`.s + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZeroInteger` + +#### Signature + +```ts ignore +export type PositiveNonZeroInteger = Cast< + N, + POSITIVE & NON_ZERO & INTEGER +>; +``` + +Casts a value into a positive nonzero integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveZero` + +#### Signature + +```ts ignore +export type PositiveZero = Cast; +``` + +Casts a value into a positive zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero, type PositiveZero } from "jsr:@type/number"; + +let x = 0 as PositiveZero, y = 1; + +if (isPositiveZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'PositiveZero'. +``` + +## `Range` + +#### Signature + +```ts ignore +export type Range< + Min extends number = number, + Max extends number = number, + Tex extends Exclusivity = never, +> = [Tex] extends [never] + ? + | RangeInclusiveMin + | RangeInclusive + | RangeInclusiveMax + | RangeExclusive + | RangeUnknown + : Either< + Extract, Required>>, + RangeUnknown + >; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `never`) + +--- + +## `RangeExclusive` + +#### Signature + +```ts ignore +export type RangeExclusive< + Min extends number = number, + Max extends number = number, +> = readonly [Min, Max, "()"] | readonly [Max, "()"]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `RangeInclusive` + +#### Signature + +```ts ignore +export type RangeInclusive< + Min extends number = number, + Max extends number = number, +> = readonly [Min, Max, "[]"] | readonly [Max, "[]"]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `RangeInclusiveMax` + +#### Signature + +```ts ignore +export type RangeInclusiveMax< + Min extends number = number, + Max extends number = number, +> = readonly [Min, Max, "(]"] | readonly [Max, "(]"]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `RangeInclusiveMin` + +#### Signature + +```ts ignore +export type RangeInclusiveMin< + Min extends number = number, + Max extends number = number, +> = readonly [Min, Max, "[)"] | readonly [Max, "[)"]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `RangeUnknown` + +#### Signature + +```ts ignore +export type RangeUnknown< + Min extends number = number, + Max extends number = number, + Tex extends Exclusivity = Exclusivity, +> = readonly [Min, Max, Tex] | readonly [Max, Tex]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `Exclusivity`) + +--- + +## `Uint16` + +#### Signature + +```ts ignore +export type Uint16 = Cast; +``` + +Casts a value into an unsigned 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `Uint32` + +#### Signature + +```ts ignore +export type Uint32 = Cast; +``` + +Casts a value into an unsigned 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `Uint8` + +#### Signature + +```ts ignore +export type Uint8 = Cast; +``` + +Casts a value into an unsigned 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint8, type Uint8 } from "@nick/is/uint8"; + +let i = 1 as Uint8, y = 0; + +if (isUint8(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint8'. +``` + +## `Unwrap` + +#### Signature + +```ts ignore +export type Unwrap = U extends Cast ? [N, T] : [U, never]; +``` + +Unwraps a type that has been cast with [Cast](#cast "Jump to symbol: 'Cast'") +into a tuple of the original value and the specific type it was cast to (or +"branded" with). If the given type was _not_ cast with +[Cast](#cast "Jump to symbol: 'Cast'"), it will resolve to a tuple containing +the original value and `never`, respectively. + +##### Type Parameters + +- **`U`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { Cast, Unwrap } from "jsr:@nick/is/number"; + +type Int_3 = Cast<3, INTEGER>; + +function unwrap(value: T): Unwrap[0] { + return value as Unwrap[0]; +} +``` + +## `Zero` + +#### Signature + +```ts ignore +export type Zero = Cast; +``` + +Casts a value into a zero type. If the value is not a number, it will resolve to +`never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isZero, type Zero } from "jsr:@type/number/zero"; + +let x = 0 as Zero, y = 1; + +if (isZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Zero'. +``` + +## `EVEN` + +### Properties + +#### IS_EVEN + +```ts +readonly IS_EVEN: true; +``` + +--- + +## `EVEN_INTEGER` + +## `FINITE` + +### Properties + +#### IS_INFINITE + +```ts +readonly IS_INFINITE: false; +``` + +#### IS_FINITE + +```ts +readonly IS_FINITE: true; +``` + +--- + +## `FLOAT` + +### Properties + +#### IS_FLOAT + +```ts +readonly IS_FLOAT: true; +``` + +--- + +## `FLOAT16` + +##### Extends `FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION: 0.5; +``` + +--- + +## `FLOAT32` + +##### Extends `FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION: 1; +``` + +--- + +## `FLOAT64` + +##### Extends `FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION: 2; +``` + +--- + +## `INFINITE` + +### Properties + +#### IS_FINITE + +```ts +readonly IS_FINITE: false; +``` + +#### IS_INFINITE + +```ts +readonly IS_INFINITE: true; +``` + +--- + +## `INT16` + +##### Extends `INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH: 16; +``` + +--- + +## `INT32` + +##### Extends `INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH: 32; +``` + +--- + +## `INT64` + +##### Extends `INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH: 64; +``` + +--- + +## `INT8` + +##### Extends `INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH: 8; +``` + +--- + +## `INTEGER` + +### Properties + +#### IS_INTEGER + +```ts +readonly IS_INTEGER: true; +``` + +--- + +## `IsInRange` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `Exclusivity`) + +--- + +### Properties + +#### RANGE + +```ts +readonly RANGE: readonly [Min,Max,Tex]; +``` + +--- + +## `MAYBE_EVEN` + +### Properties + +#### IS_EVEN + +```ts +readonly IS_EVEN?: true; +``` + +--- + +## `MAYBE_EVEN_INTEGER` + +## `MAYBE_FINITE` + +### Properties + +#### IS_INFINITE + +```ts +readonly IS_INFINITE?: false; +``` + +#### IS_FINITE + +```ts +readonly IS_FINITE?: true; +``` + +--- + +## `MAYBE_FLOAT` + +### Properties + +#### IS_FLOAT + +```ts +readonly IS_FLOAT?: true; +``` + +--- + +## `MAYBE_FLOAT16` + +##### Extends `MAYBE_FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION?: 0.5; +``` + +--- + +## `MAYBE_FLOAT32` + +##### Extends `MAYBE_FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION?: 1; +``` + +--- + +## `MAYBE_FLOAT64` + +##### Extends `MAYBE_FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION?: 2; +``` + +--- + +## `MAYBE_INFINITE` + +### Properties + +#### IS_FINITE + +```ts +readonly IS_FINITE?: false; +``` + +#### IS_INFINITE + +```ts +readonly IS_INFINITE?: true; +``` + +--- + +## `MAYBE_INT16` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH?: 16; +``` + +--- + +## `MAYBE_INT32` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH?: 32; +``` + +--- + +## `MAYBE_INT64` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH?: 64; +``` + +--- + +## `MAYBE_INT8` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH?: 8; +``` + +--- + +## `MAYBE_INTEGER` + +### Properties + +#### IS_INTEGER + +```ts +readonly IS_INTEGER?: true; +``` + +--- + +## `MAYBE_NAN` + +### Properties + +#### IS_NAN + +```ts +readonly IS_NAN?: true; +``` + +--- + +## `MAYBE_NEGATIVE` + +### Properties + +#### IS_POSITIVE + +```ts +readonly IS_POSITIVE?: false; +``` + +#### IS_NEGATIVE + +```ts +readonly IS_NEGATIVE?: true; +``` + +--- + +## `MAYBE_NEGATIVE_FINITE` + +## `MAYBE_NEGATIVE_INFINITY` + +## `MAYBE_NEGATIVE_INTEGER` + +## `MAYBE_NEGATIVE_NON_ZERO_FINITE` + +## `MAYBE_NEGATIVE_NON_ZERO_INTEGER` + +## `MAYBE_NEGATIVE_ZERO` + +## `MAYBE_NON_ZERO` + +### Properties + +#### IS_ZERO + +```ts +readonly IS_ZERO?: false; +``` + +#### IS_NON_ZERO + +```ts +readonly IS_NON_ZERO?: true; +``` + +--- + +## `MAYBE_NON_ZERO_FINITE` + +## `MAYBE_NON_ZERO_INTEGER` + +## `MAYBE_ODD` + +### Properties + +#### IS_ODD + +```ts +readonly IS_ODD?: true; +``` + +--- + +## `MAYBE_ODD_INTEGER` + +## `MAYBE_POSITIVE` + +### Properties + +#### IS_NEGATIVE + +```ts +readonly IS_NEGATIVE?: false; +``` + +#### IS_POSITIVE + +```ts +readonly IS_POSITIVE?: true; +``` + +--- + +## `MAYBE_POSITIVE_FINITE` + +## `MAYBE_POSITIVE_INFINITY` + +## `MAYBE_POSITIVE_INTEGER` + +## `MAYBE_POSITIVE_NON_ZERO_FINITE` + +## `MAYBE_POSITIVE_NON_ZERO_INTEGER` + +## `MAYBE_POSITIVE_ODD_INTEGER` + +## `MAYBE_POSITIVE_ZERO` + +## `MAYBE_UINT16` + +## `MAYBE_UINT32` + +## `MAYBE_UINT64` + +## `MAYBE_UINT8` + +## `MAYBE_UNSIGNED` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### IS_UNSIGNED + +```ts +readonly IS_UNSIGNED?: true; +``` + +--- + +## `MAYBE_ZERO` + +### Properties + +#### IS_NON_ZERO + +```ts +readonly IS_NON_ZERO?: false; +``` + +#### IS_ZERO + +```ts +readonly IS_ZERO?: true; +``` + +--- + +## `NAN` + +### Properties + +#### IS_NAN + +```ts +readonly IS_NAN: true; +``` + +--- + +## `NEGATIVE` + +### Properties + +#### IS_POSITIVE + +```ts +readonly IS_POSITIVE: false; +``` + +#### IS_NEGATIVE + +```ts +readonly IS_NEGATIVE: true; +``` + +--- + +## `NEGATIVE_FINITE` + +## `NEGATIVE_INFINITY` + +## `NEGATIVE_INTEGER` + +## `NEGATIVE_NON_ZERO_FINITE` + +## `NEGATIVE_NON_ZERO_INTEGER` + +## `NEGATIVE_ZERO` + +## `NON_ZERO` + +### Properties + +#### IS_ZERO + +```ts +readonly IS_ZERO: false; +``` + +#### IS_NON_ZERO + +```ts +readonly IS_NON_ZERO: true; +``` + +--- + +## `NON_ZERO_FINITE` + +## `NON_ZERO_INTEGER` + +## `ODD` + +### Properties + +#### IS_ODD + +```ts +readonly IS_ODD: true; +``` + +--- + +## `ODD_INTEGER` + +## `POSITIVE` + +### Properties + +#### IS_NEGATIVE + +```ts +readonly IS_NEGATIVE: false; +``` + +#### IS_POSITIVE + +```ts +readonly IS_POSITIVE: true; +``` + +--- + +## `POSITIVE_FINITE` + +## `POSITIVE_INFINITY` + +## `POSITIVE_INTEGER` + +## `POSITIVE_NON_ZERO_FINITE` + +## `POSITIVE_NON_ZERO_INTEGER` + +## `POSITIVE_ODD_INTEGER` + +## `POSITIVE_ZERO` + +## `UINT16` + +## `UINT32` + +## `UINT64` + +## `UINT8` + +## `UNSIGNED` + +##### Extends `INTEGER` + +### Properties + +#### IS_UNSIGNED + +```ts +readonly IS_UNSIGNED: true; +``` + +--- + +## `ZERO` + +### Properties + +#### IS_NON_ZERO + +```ts +readonly IS_NON_ZERO: false; +``` + +#### IS_ZERO + +```ts +readonly IS_ZERO: true; +``` + +--- diff --git a/docs/object-like.md b/docs/object-like.md new file mode 100644 index 0000000..664be1e --- /dev/null +++ b/docs/object-like.md @@ -0,0 +1,41 @@ +# @nick/is/object-like + +## `isObjectLike` + +#### Signature + +```ts ignore +function isObjectLike(it: unknown): it is object; +``` + +Check if a given value is a non-null object-like value, which includes plain +objects, arrays, functions, classes, class instances, and other objects. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if it is a non-null object-like value, `false` otherwise. + +###### Category + +`Objects` + +#### Examples + +```ts +import { isObjectLike } from "jsr:@nick/is/object-like"; + +console.log(isObjectLike({})); // true +console.log(isObjectLike([])); // true +console.log(isObjectLike(() => {})); // true +console.log(isObjectLike(new class {}())); // true +console.log(isObjectLike(new Object())); // true +console.log(isObjectLike(null)); // false +console.log(isObjectLike(undefined)); // false +console.log(isObjectLike(1)); // false +``` diff --git a/docs/object.md b/docs/object.md new file mode 100644 index 0000000..4349b9b --- /dev/null +++ b/docs/object.md @@ -0,0 +1,41 @@ +# @nick/is/object + +## `isObject` + +#### Signature + +```ts ignore +function isObject(it: unknown): it is object; +``` + +Check if the given value is a non-null object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a non-null object, `false` otherwise. + +###### Category + +`Objects` + +#### Examples + +```ts +import { isObject } from "jsr:@nick/is/object"; + +console.log(isObject({})); // true +console.log(isObject(new class {}())); // true +console.log(isObject(new Object())); // true +console.log(isObject([])); // true + +console.log(isObject(() => {})); // false +console.log(isObject(null)); // false +console.log(isObject(undefined)); // false +console.log(isObject(1)); // false +``` diff --git a/docs/plain-object.md b/docs/plain-object.md new file mode 100644 index 0000000..4d52e8c --- /dev/null +++ b/docs/plain-object.md @@ -0,0 +1,42 @@ +# @nick/is/plain-object + +## `isPlainObject` + +#### Signature + +```ts ignore +function isPlainObject>(it: unknown): it is T; +``` + +Check if the given value is a plain object, which is an object that either has a +prototype of `null` or `Object.prototype`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a plain object, `false` otherwise. + +###### Category + +`Objects` + +#### Examples + +```ts +import { isPlainObject } from "jsr:@nick/is/plain-object"; + +console.log(isPlainObject({})); // true +console.log(isPlainObject(new class {}())); // true +console.log(isPlainObject(new Object())); // true + +console.log(isPlainObject([])); // false +console.log(isPlainObject(() => {})); // false +console.log(isPlainObject(null)); // false +console.log(isPlainObject(undefined)); // false +console.log(isPlainObject(1)); // false +``` diff --git a/docs/present.md b/docs/present.md new file mode 100644 index 0000000..e245d94 --- /dev/null +++ b/docs/present.md @@ -0,0 +1,56 @@ +# @nick/is/present + +## `isPresent` + +#### Signature + +```ts ignore +function isPresent(it: T | null | undefined): it is NonNullable; +``` + +Check if the given value is not `null` or `undefined`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is not null or undefined, or `false` otherwise. + +###### Category + +`Primitives` + +###### See Also + +- [isMissing](#ismissing "Jump to symbol: 'isMissing'") for the opposite of this + function. + +#### Examples + +```ts +import { isPresent } from "jsr:@nick/is/present"; + +isPresent(null); // false +isPresent(undefined); // false +isPresent(0); // true +isPresent(""); // true +isPresent(false); // true +``` + +## `NonNullable` + +#### Signature + +```ts ignore +export type NonNullable = T & {}; +``` + +##### Type Parameters + +- **`T`** + +--- diff --git a/docs/primitive.md b/docs/primitive.md new file mode 100644 index 0000000..e4df70e --- /dev/null +++ b/docs/primitive.md @@ -0,0 +1,67 @@ +# @nick/is/primitive + +## `isPrimitive` + +#### Signature + +```ts ignore +function isPrimitive(it: unknown): it is Primitive; +``` + +Checks if a given value is a primitive string, number, bigint, boolean, symbol, +null, or undefined. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a primitive, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isPrimitive } from "jsr:@nick/is/primitive"; + +isPrimitive("foo"); // true +isPrimitive(42); // true +isPrimitive(BigInt(42)); // true +isPrimitive(true); // true +isPrimitive(Symbol("foo")); // true +isPrimitive(null); // true +isPrimitive(undefined); // true + +isPrimitive({}); // false +isPrimitive(new String("foo")); // false +isPrimitive(new Number(42)); // false +isPrimitive(new Boolean(true)); // false +``` + +## `Primitive` + +#### Signature + +```ts ignore +export type Primitive = + | string + | number + | bigint + | boolean + | symbol + | null + | undefined; +``` + +Represents a primitive value. This includes strings, numbers, bigints, booleans, +symbols, null, and undefined. + +###### Category + +`Primitives` diff --git a/docs/printable.md b/docs/printable.md new file mode 100644 index 0000000..2ac689a --- /dev/null +++ b/docs/printable.md @@ -0,0 +1,72 @@ +# @nick/is/printable + +## `isPrintable` + +#### Signature + +```ts ignore +function isPrintable(x: unknown): x is Printable; +``` + +Check if a value is printable, meaning it is either a `string`, `number`, +`bigint`, `boolean`, `null` or `undefined`. This is useful for logging and +debugging purposes. The complentary type +[`Printable`](#printable "Jump to symbol: 'Printable'") can be used on the +type-level to represent values that are usable within a template literal type +syntax. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is printable, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isPrintable } from "jsr:@nick/is/printable"; + +console.log(isPrintable("hello")); // true +console.log(isPrintable(1)); // true +console.log(isPrintable(BigInt(1))); // true +console.log(isPrintable(true)); // true +console.log(isPrintable(null)); // true +console.log(isPrintable(undefined)); // true +console.log(isPrintable({})); // false +console.log(isPrintable(Symbol())); // false +``` + +## `Printable` + +#### Signature + +```ts ignore +export type Printable = string | number | bigint | boolean | null | undefined; +``` + +Represents a value that can be printed in a template literal type string, which +means it is either a `string`, `number`, `bigint`, `boolean`, `null` or +`undefined`. Any other type of value will raise a compiler error if you attempt +to construct a template literal type with it. + +#### Examples + +```ts +import type { Printable } from "jsr:@nick/is/printable"; + +type Join = T extends + [infer F extends Printable, ...infer R] + ? `${F}${R extends [] ? "" : D}${Join}` + : ""; + +type Result = Join<[1, "two", 3n, true, null, undefined]>; +// ^? type Result = "1two3true" +``` diff --git a/docs/promise-like.md b/docs/promise-like.md new file mode 100644 index 0000000..355ba19 --- /dev/null +++ b/docs/promise-like.md @@ -0,0 +1,37 @@ +# @nick/is/promise-like + +## `isPromiseLike` + +#### Signature + +```ts ignore +function isPromiseLike(it: unknown): it is PromiseLike; +``` + +Check if the given value is a `PromiseLike` type, which includes both native +`Promise` instances and custom promise-like objects with a `.then` method +(sometimes referred to as "thenables"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `PromiseLike`, `false` otherwise. + +###### Category + +`Async/Await` + +#### Examples + +```ts +import { isPromiseLike } from "jsr:@nick/is/promise-like"; + +console.log(isPromiseLike(Promise.resolve())); // true +console.log(isPromiseLike({ then: () => {} })); // true +console.log(isPromiseLike({})); // false +``` diff --git a/docs/promise.md b/docs/promise.md new file mode 100644 index 0000000..36a9b3d --- /dev/null +++ b/docs/promise.md @@ -0,0 +1,40 @@ +# @nick/is/promise + +## `isPromise` + +#### Signature + +```ts ignore +function isPromise(it: unknown): it is Promise; +``` + +Checks if a given value is a native `Promise` instance. This is a more reliable +alternative to `it instanceof Promise` because it also works across different +realms (e.g., iframes, workers, etc.). + +Note: This guard does not consider custom promise-like objects with `.then` +methods to be promises. If your use case requires that, use `isPromiseLike`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Promise`, `false` otherwise. + +###### Category + +`Async/Await` + +#### Examples + +```ts +import { isPromise } from "jsr:@nick/is/promise"; + +console.log(isPromise(Promise.resolve())); // true +console.log(isPromise({ then: () => {} })); // false +console.log(isPromise({})); // false +``` diff --git a/docs/property-key.md b/docs/property-key.md new file mode 100644 index 0000000..88f39a3 --- /dev/null +++ b/docs/property-key.md @@ -0,0 +1,56 @@ +# @nick/is/property-key + +## `isPropertyKey` + +#### Signature + +```ts ignore +function isPropertyKey(value: unknown): value is PropertyKey; +``` + +Checks if the given value is of the `PropertyKey` type (i.e. string, number, or +symbol). + +In JavaScript, a property key can technically only be a string or a symbol, and +all other values are coerced to strings. TypeScript includes numbers in its +definition of this type, and therefore so does this function. But it is worth +noting that even though a number _can_ be used to indexed access an array-like +object, the number is coerced to a string behind the scenes. + +##### Parameters + +| Name | Info | +| :---------- | :------------------ | +| **`value`** | The value to check. | + +##### Returns + +`true` if the value is a property key, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isPropertyKey } from "jsr:@nick/is/property-key"; + +isPropertyKey("foo"); // true +isPropertyKey(42); // true +isPropertyKey(Symbol("foo")); // true +isPropertyKey({ foo: "bar" }); // false +``` + +## `PropertyKey` + +#### Signature + +```ts ignore +export type PropertyKey = string | number | symbol; +``` + +The `PropertyKey` type represents the set of all possible values that can be +used as a property key in JavaScript. This includes strings, numbers, and +symbols. This type is included in TypeScript's standard library, but for the +situations where it may not be available, it's also exported from this module. diff --git a/docs/readable-stream.md b/docs/readable-stream.md new file mode 100644 index 0000000..e838dd8 --- /dev/null +++ b/docs/readable-stream.md @@ -0,0 +1,40 @@ +# @nick/is/readable-stream + +## `isReadableStream` + +#### Signature + +```ts ignore +function isReadableStream(it: unknown): it is ReadableStream; +``` + +Checks if [it](#it "Jump to symbol: 'it'") is a `ReadableStream` object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `ReadableStream`, `false` otherwise. + +###### Category + +`Streams` + +#### Examples + +```ts +import { isReadableStream } from "jsr:@nick/is/readable-stream"; + +const stream = new ReadableStream(); +isReadableStream(stream); // true + +const stream2 = new TransformStream(); +isReadableStream(stream2); // false + +const stream3 = new WritableStream(); +isReadableStream(stream3); // false +``` diff --git a/docs/reader-sync.md b/docs/reader-sync.md new file mode 100644 index 0000000..67ef4a2 --- /dev/null +++ b/docs/reader-sync.md @@ -0,0 +1,76 @@ +# @nick/is/reader-sync + +## `isReaderSync` + +#### Signature + +```ts ignore +function isReaderSync(it: unknown): it is ReaderSync; +``` + +Checks if a given value is a synchronous reader, which is an object that +implements the `readSync` method as per Deno's `ReaderSync` interface. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a synchronous Reader, `false` otherwise. + +###### Category + +`I/O` + +#### Examples + +```ts +import { isReaderSync } from "jsr:@nick/is/reader-sync"; + +const file = Deno.openSync("file.txt"); +isReaderSync(file); // true + +const socket = new WebSocket("ws://example.com"); +isReaderSync(socket); // false +``` + +## `ReaderSync` + +An abstract interface which when implemented provides an interface to read bytes +into an array buffer synchronously. + +###### Category + +`I/O` + +### Methods + +#### readSync + +```ts +readSync( + p: Uint8Array, + ): number | null; +``` + +Reads up to `p.byteLength` bytes into `p`. It resolves to the number of bytes +read (`0` < `n` <= `p.byteLength`) and rejects if any error encountered. Even if +`readSync()` returns `n` < `p.byteLength`, it may use all of `p` as scratch +space during the call. If some data is available but not `p.byteLength` bytes, +`readSync()` conventionally returns what is available instead of waiting for +more. + +When `readSync()` encounters end-of-file condition, it returns EOF (`null`). + +When `readSync()` encounters an error, it throws with an error. + +Callers should always process the `n` > `0` bytes returned before considering +the EOF (`null`). Doing so correctly handles I/O errors that happen after +reading some bytes and also both of the allowed EOF behaviors. + +Implementations should not retain a reference to `p`. + +--- diff --git a/docs/reader.md b/docs/reader.md new file mode 100644 index 0000000..a14df4d --- /dev/null +++ b/docs/reader.md @@ -0,0 +1,75 @@ +# @nick/is/reader + +## `isReader` + +#### Signature + +```ts ignore +function isReader(it: unknown): it is Reader; +``` + +Checks if a given value is an asynchronous reader, which is an object that +implements the `read` method as per Deno's `Reader` interface. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an asynchronous Reader, `false` otherwise. + +###### Category + +`I/O` + +#### Examples + +```ts +import { isReader } from "jsr:@nick/is/reader"; + +const file = await Deno.open("file.txt"); +isReader(file); // true + +const socket = new WebSocket("ws://example.com"); +isReader(socket); // false +``` + +## `Reader` + +An abstract interface which when implemented provides an interface to read bytes +into an array buffer asynchronously. + +###### Category + +`I/O` + +### Methods + +#### read + +```ts +read( + p: Uint8Array, + ): Promise; +``` + +Reads up to `p.byteLength` bytes into `p`. It resolves to the number of bytes +read (`0` < `n` <= `p.byteLength`) and rejects if any error encountered. Even if +`read()` resolves to `n` < `p.byteLength`, it may use all of `p` as scratch +space during the call. If some data is available but not `p.byteLength` bytes, +`read()` conventionally resolves to what is available instead of waiting for +more. + +When `read()` encounters end-of-file condition, it resolves to EOF (null). When +`read()` encounters an error, it rejects with an error. + +Callers should always process the `n` > `0` bytes returned before considering +the EOF (`null`). Doing so correctly handles I/O errors that happen after +reading some bytes and also both of the allowed EOF behaviors. + +Implementations should not retain a reference to `p`. + +--- diff --git a/docs/regexp.md b/docs/regexp.md new file mode 100644 index 0000000..c860c5e --- /dev/null +++ b/docs/regexp.md @@ -0,0 +1,37 @@ +# @nick/is/regexp + +## `isRegExp` + +#### Signature + +```ts ignore +function isRegExp(it: unknown): it is RegExp; +``` + +Check if the given value is a regular expression, which is an object that +represents a pattern of text that can be used to perform pattern matching with +strings. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a regular expression, `false` otherwise. + +###### Category + +`Standard` + +#### Examples + +```ts +import { isRegExp } from "jsr:@nick/is/regexp"; + +const regex = /foo/; +console.log(isRegExp(regex)); // true +console.log(isRegExp("foo")); // false +``` diff --git a/docs/registered-symbol.md b/docs/registered-symbol.md new file mode 100644 index 0000000..1e13778 --- /dev/null +++ b/docs/registered-symbol.md @@ -0,0 +1,122 @@ +# @nick/is/registered-symbol + +## `isRegisteredSymbol` + +#### Signature + +```ts ignore +function isRegisteredSymbol(it: unknown): it is RegisteredSymbol; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a registered symbol, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isRegisteredSymbol } from "jsr:@nick/is/registered-symbol"; + +isRegisteredSymbol(Symbol.for("foo")); // true + +isRegisteredSymbol(Symbol("foo")); // false +isRegisteredSymbol(Symbol.iterator); // false +isRegisteredSymbol("@@foo"); // false +``` + +```ts +import { + isRegisteredSymbol, + type RegisteredSymbol, +} from "jsr:@nick/is/registered-symbol"; + +function doSomething(key: RegisteredSymbol): void { + if (isRegisteredSymbol(key)) { + // ... do something ... + } +} + +const key = Symbol.for("foo"); +doSomething(key); +``` + +```ts +import { + isRegisteredSymbol, + RegisteredSymbol, +} from "jsr:@nick/is/registered-symbol"; + +function assertRegisteredSymbol( + value: unknown, +): asserts value is RegisteredSymbol { + if (!isRegisteredSymbol(value)) { + throw new Error("Expected a registered symbol."); + } +} +``` + +## `RegisteredSymbol` + +#### Signature + +```ts ignore +export type RegisteredSymbol = Brand; +``` + +Branded type representing a symbol that is registered in the global symbol +registry, which means it was created using the `Symbol.for()` function. This +kind of symbol is **not** allowed as keys in Weak Collections like `WeakMap` or +`WeakSet` objects, as they are not truly unique. + +This is the type that the +[`isRegisteredSymbol`](#isregisteredsymbol "Jump to symbol: 'isRegisteredSymbol'") +type guard narrows its input values to. It is provided as an export for you to +use in tandem with that type guard, to ensure your code is handling registered +symbols in a strict, type-safe manner. + +###### Categories + +`Primitives` `Types` + +#### Examples + +```ts +import { + isRegisteredSymbol, + type RegisteredSymbol, +} from "jsr:@nick/is/registered-symbol"; + +function doSomething(key: RegisteredSymbol): void { + // ... +} + +const key = Symbol.for("foo"); +if (isRegisteredSymbol(key)) { + doSomething(key); +} +``` + +```ts +import { + isRegisteredSymbol, + type RegisteredSymbol, +} from "jsr:@nick/is/registered-symbol"; + +function assertRegisteredSymbol( + value: unknown, +): asserts value is RegisteredSymbol { + if (!isRegisteredSymbol(value)) { + throw new Error("Expected a registered symbol."); + } +} +``` diff --git a/docs/semver.md b/docs/semver.md new file mode 100644 index 0000000..9f2959e --- /dev/null +++ b/docs/semver.md @@ -0,0 +1,73 @@ +# @nick/is/semver + +## `isSemVer` + +#### Signature + +```ts ignore +function isSemVer(it: unknown): it is SemVer; +``` + +Check if the given value is a valid semantic version string, according to the +Semantic Versioning 2.0.0 specification as per https://semver.org. This function +does not check if the version is a valid version range, but simply validates it +against the regular expression pattern from the specification. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if it is a valid semantic version string, `false` otherwise. + +###### Category + +`Strings` + +#### Examples + +```ts +import { isSemVer } from "jsr:@nick/is/semver"; + +console.log(isSemVer("1.2.3")); // true +console.log(isSemVer("1.2.3-alpha")); // true +console.log(isSemVer("1.2.3+build")); // true +console.log(isSemVer("1.2.3-alpha+build")); // true +console.log(isSemVer("1.2.3-alpha.1")); // true +console.log(isSemVer("1.2")); // false +``` + +## `MaybeSemVer` + +#### Signature + +```ts ignore +export type MaybeSemVer = Flavor; +``` + +Less-strict form of the [`SemVer`](#semver "Jump to symbol: 'SemVer'") type, +which allows for strings to be assigned to it that might not be valid semantic +version strings. + +###### Category + +`Strings` + +## `SemVer` + +#### Signature + +```ts ignore +export type SemVer = Brand; +``` + +Represents a validated Semantic Version (SemVer v2.0.0) string. This is the type +the [`isSemVer`](#issemver "Jump to symbol: 'isSemVer'") function narrows its +input values to. + +###### Category + +`Strings` diff --git a/docs/set-iterator.md b/docs/set-iterator.md new file mode 100644 index 0000000..9dbe63c --- /dev/null +++ b/docs/set-iterator.md @@ -0,0 +1,60 @@ +# @nick/is/set-iterator + +## `isSetIterator` + +#### Signature + +```ts ignore +function isSetIterator(it: unknown): it is SetIterator; +``` + +Check if the given value is a set iterator, which is an iterable iterator that +yields key-value pairs from a Set object. This is the type of object returned by +the `Set.prototype.entries` and `Set.prototype[Symbol.iterator]` methods. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a set iterator, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isSetIterator } from "jsr:@nick/is/set-iterator"; + +const set = new Set(["foo", "bar", "foo"]); +const iter = set[Symbol.iterator](); +console.log(isSetIterator(iterator)); // true +console.log(isSetIterator(set)); // false +``` + +## `SetIterator` + +Represents a set iterator. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +##### Extends `IterableIterator` + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "Set Iterator" | "Set Entries"; +``` + +--- diff --git a/docs/set-like.md b/docs/set-like.md new file mode 100644 index 0000000..51d8773 --- /dev/null +++ b/docs/set-like.md @@ -0,0 +1,765 @@ +# @nick/is/set-like + +## `isExtendedSetLike` + +#### Signature + +```ts ignore +function isExtendedSetLike(it: unknown): it is ExtendedSetLike; +``` + +Checks whether the provided value is a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object. The `ExtendedSetLike` interface is the full implementation of a +`ExtendedSetLike` object, including all the composition methods like `union`, +`intersection`, `difference`, and `symmetricDifference`. + +The `ExtendedSetLike` type is the shape of the native `Set` object in JavaScript +**after** the introduction of the TC39 Proposal for Set Methods, which added the +composition methods to the API. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object; otherwise, `false`. + +###### Category + +`Guards` + +## `isExtendedSetLikeConstructor` + +#### Signature + +```ts ignore +function isExtendedSetLikeConstructor( + it: unknown, +): it is ExtendedSetLikeConstructor; +``` + +Checks if a given value appears to be a +[`ExtendedSetLikeConstructor`](#extendedsetlikeconstructor "Jump to symbol: 'ExtendedSetLikeConstructor'") +function, including a `prototype` property that appears to be a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a +[`ExtendedSetLikeConstructor`](#extendedsetlikeconstructor "Jump to symbol: 'ExtendedSetLikeConstructor'") +function; otherwise, `false`. + +###### Category + +`Guards` + +## `isReadonlyCollection` + +#### Signature + +```ts ignore +function isReadonlyCollection(it: unknown): it is ReadonlyCollection; +``` + +Checks whether the provided value is a +[`ReadonlyCollection`](#readonlycollection "Jump to symbol: 'ReadonlyCollection'") +object. The `ReadonlyCollection` interface is the minimum requirement for a +value to be used in the composition methods found in `ExtendedSetLike` +implementations, such as `union`, `intersection`, `difference`, and +`symmetricDifference`. + +This type is the **bare minimal** requirement for a value to be considered a +"set-like" object in JavaScript, and only requires the `has`, `keys`, and `size` +members to be present. As such, native `Set` objects and also native `Map` +objects both qualify as `ReadonlyCollection` objects. For a more specific check, +see [`isSetLike`](#issetlike "Jump to symbol: 'isSetLike'") or +[`isExtendedSetLike`](#isextendedsetlike "Jump to symbol: 'isExtendedSetLike'"), +which check for the full API of a Set object, with or without the composition +methods added by the TC39 proposal, respectively. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a +[`ReadonlyCollection`](#readonlycollection "Jump to symbol: 'ReadonlyCollection'") +object; otherwise, `false`. + +###### Category + +`Guards` + +## `isReadonlyCollectionConstructor` + +#### Signature + +```ts ignore +function isReadonlyCollectionConstructor( + it: unknown, +): it is ReadonlyCollectionConstructor; +``` + +Checks if a given value appears to be a +[`ReadonlyCollectionConstructor`](#readonlycollectionconstructor "Jump to symbol: 'ReadonlyCollectionConstructor'") +function, including a `prototype` property that appears to be a +[`ReadonlyCollection`](#readonlycollection "Jump to symbol: 'ReadonlyCollection'") +object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value appears to be a +[`ReadonlyCollectionConstructor`](#readonlycollectionconstructor "Jump to symbol: 'ReadonlyCollectionConstructor'") +function; otherwise, `false`. + +###### Category + +`Guards` + +## `isSetLike` + +#### Signature + +```ts ignore +function isSetLike(it: unknown): it is SetLike; +``` + +Checks whether the provided value is a +[`SetLike`](#setlike "Jump to symbol: 'SetLike'") object. The `SetLike` +interface is the base implementation of a `ExtendedSetLike` object, without any +additional composition methods like `union` or `intersection`. + +This type is the shape of the native `Set` object in JavaScript **prior** to the +introduction of the TC39 Proposal for Set Methods, which added the composition +methods to the API. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a [`SetLike`](#setlike "Jump to symbol: 'SetLike'") +object; otherwise, `false`. + +###### Category + +`Guards` + +## `isSetLikeConstructor` + +#### Signature + +```ts ignore +function isSetLikeConstructor(it: unknown): it is SetLikeConstructor; +``` + +Checks if a given value appears to be a +[`SetLikeConstructor`](#setlikeconstructor "Jump to symbol: 'SetLikeConstructor'") +function, including a `prototype` property that appears to be a +[`SetLike`](#setlike "Jump to symbol: 'SetLike'") object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a +[`SetLikeConstructor`](#setlikeconstructor "Jump to symbol: 'SetLikeConstructor'") +function; otherwise, `false`. + +###### Category + +`Guards` + +## `SupportedSetLike` + +#### Signature + +```ts ignore +export type SupportedSetLike = + Exclude, keyof SetLike> extends + keyof globalThis.Set ? ExtendedSetLike : SetLike; +``` + +This type represents either the full +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +interface, or the [`SetLike`](#setlike "Jump to symbol: 'SetLike'") interface, +depending on whether the current environment supports composition methods +introduced by the TC39 Set Methods Proposal. + +If the current environment supports the composition methods, this type will +resolve to the +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +interface. Otherwise, it will resolve to the +[`SetLike`](#setlike "Jump to symbol: 'SetLike'") interface. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +###### See Also + +- [`SupportedSetLikeConstructor`](#supportedsetlikeconstructor "Jump to symbol: 'SupportedSetLikeConstructor'") + for a similar type that represents the constructor function for the supported + set-like object. + +## `SupportedSetLikeConstructor` + +#### Signature + +```ts ignore +export type SupportedSetLikeConstructor = + Exclude extends + keyof globalThis.SetConstructor ? ExtendedSetLikeConstructor + : SetLikeConstructor; +``` + +This type represents either the full +[`ExtendedSetLikeConstructor`](#extendedsetlikeconstructor "Jump to symbol: 'ExtendedSetLikeConstructor'") +interface, or the +[`SetLikeConstructor`](#setlikeconstructor "Jump to symbol: 'SetLikeConstructor'") +interface, depending on whether the current environment supports composition +methods introduced by the TC39 Set Methods Proposal. + +If the current environment supports the composition methods, this type will +resolve to the +[`ExtendedSetLikeConstructor`](#extendedsetlikeconstructor "Jump to symbol: 'ExtendedSetLikeConstructor'") +interface. Otherwise, it will resolve to the +[`SetLikeConstructor`](#setlikeconstructor "Jump to symbol: 'SetLikeConstructor'") +interface. + +###### See Also + +- [`SupportedSetLike`](#supportedsetlike "Jump to symbol: 'SupportedSetLike'") + for a similar type that represents the full set-like object. + +## `ExtendedSetLike` + +A `ExtendedSetLike` object is a collection of values, where each value may only +occur once. The values in a `ExtendedSetLike` can be either primitive values or +object references. The keys of a `ExtendedSetLike` are the same as the values. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +##### Extends `SetLike` + +### Methods + +#### union + +```ts +union( + other: ReadonlyCollection, + ): ExtendedSetLike; +``` + +##### Parameters + +| Name | Info | +| :---------- | :------------------------------------------------ | +| **`other`** | The other set-like object to merge with this one. | + +##### Returns + +a new [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object containing all the elements in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +and also all the elements in the [`other`](#other "Jump to symbol: 'other'"). + +#### intersection + +```ts +intersection( + other: ReadonlyCollection, + ): ExtendedSetLike; +``` + +##### Parameters + +| Name | Info | +| :---------- | :---------------------------------------------------- | +| **`other`** | The other set-like object to intersect with this one. | + +##### Returns + +a new [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object containing all the elements which are both in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +and in the [`other`](#other "Jump to symbol: 'other'"). + +#### difference + +```ts +difference( + other: ReadonlyCollection, + ): ExtendedSetLike; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a new [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object containing all the elements in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +which are not also in the [`other`](#other "Jump to symbol: 'other'"). + +#### symmetricDifference + +```ts +symmetricDifference( + other: ReadonlyCollection, + ): ExtendedSetLike; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a new ExtendedSetLike object containing all the elements which are in either +this [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object or in the [`other`](#other "Jump to symbol: 'other'"), but not in both. + +#### isSubsetOf + +```ts +isSubsetOf( + other: ReadonlyCollection, + ): boolean; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a boolean indicating whether all the elements in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +are also in the [`other`](#other "Jump to symbol: 'other'"). + +#### isSupersetOf + +```ts +isSupersetOf( + other: ReadonlyCollection, + ): boolean; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a boolean indicating whether all the elements in the +[`other`](#other "Jump to symbol: 'other'") are also in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object. + +#### isDisjointFrom + +```ts +isDisjointFrom( + other: ReadonlyCollection, + ): boolean; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a boolean indicating whether this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +has no elements in common with the [`other`](#other "Jump to symbol: 'other'"). + +--- + +## `ExtendedSetLikeConstructor` + +Represents a constructor function for an +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object. + +### Properties + +#### prototype + +```ts +readonly prototype: ExtendedSetLike; +``` + +--- + +## `ReadonlyCollection` + +Set-like objects are collections of unique values (each value may only occur +once). The `ReadonlyCollection` interface defines the bare minimum requirements +for an object to be considered "set-like" in JavaScript; that is, it must have: + +- a `has` method, which tests whether a given value is present in the set, + returning a boolean value indicating the result. +- a `keys` method, which returns an `IterableIterator` for the keys present in + the set. Since set collections are keyed by their values, the `keys` method + actually iterates over the **_values_** in the set. +- a read-only `size` property (getter), which returns the number of values in + the set at any given time. + +This interface the base for the `SetLike` interface (hence its name), which +extends it with additional methods like `add`, `delete`, `clear`, `forEach`, +`values`, and `entries` to provide a more complete API for working with Set- +like collections in JavaScript. Prior to the TC39 Proposal for Set Methods, the +`SetLike` interface was the shape of the native `Set` API in JavaScript. + +Following the introduction of the TC39 Proposal for Set Methods, the methods for +set composition (`union`, `intersection`, `difference`, etc.) were added to the +`Set` API, which necessitated the creation of the `ExtendedSetLike` interface to +represent the full API for set-like collections in JavaScript. + +Those methods require their arguments to implement the +[`ReadonlyCollection`](#readonlycollection "Jump to symbol: 'ReadonlyCollection'") +interface, rather than the full +[`SetLike`](#setlike "Jump to symbol: 'SetLike'") or +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'"). This +means you can call `Set.prototype.union` with a `Set`, `Map`, or even an +`IterableWeakSet` object, since they all implement the `ReadonlyCollection` API. + +###### See Also + +- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +### Properties + +#### size + +```ts +readonly size: number; +``` + +##### Returns + +The number of elements in the collection. + +--- + +### Methods + +#### has + +```ts +has(value: T): boolean; +``` + +Tests whether a given value is present in the collection. + +##### Parameters + +| Name | Info | +| :---------- | :------------------- | +| **`value`** | The value to lookup. | + +##### Returns + +`true` if the value is in the collection; otherwise, `false`. + +#### keys + +```ts +keys(): IterableIterator; +``` + +Gets an `IterableIterator` for the keys present in the collection. + +##### Returns + +An iterator of the keys in the collection. + +--- + +## `ReadonlyCollectionConstructor` + +Represents a constructor function for a +[`ReadonlyCollection`](#readonlycollection "Jump to symbol: 'ReadonlyCollection'") +object, which is the base implementation of a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object, without any of the additional composition methods like `union` or +`intersection`. + +###### See Also + +- [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") for + the full interface with composition methods. +- [`SetLike`](#setlike "Jump to symbol: 'SetLike'") for the core interface + without composition methods. + +### Properties + +#### prototype + +```ts +readonly prototype: ReadonlyCollection; +``` + +--- + +## `SetLike` + +Represents the core functionality of a `SetLike` object, which is the base +implementation of a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object, without any additional composition methods (`union`, `intersection`, +`difference`, etc). This was the native `Set` API prior to the TC39 Set Methods +Proposal's introduction. + +###### See Also + +- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set +- [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") for + the full interface with composition methods. +- [`SetLikeConstructor`](#setlikeconstructor "Jump to symbol: 'SetLikeConstructor'") + for the constructor interface. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +##### Extends `Iterable`, `ReadonlyCollection` + +### Properties + +#### size + +```ts +readonly size: number; +``` + +##### Returns + +The number of elements in the collection. + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: string; +``` + +--- + +### Methods + +#### add + +```ts +add(value: T): this; +``` + +Adds the given value to the collection, if it does not already exist. + +##### Parameters + +| Name | Info | +| :---------- | :---------------- | +| **`value`** | The value to add. | + +##### Returns + +The collection. + +#### has + +```ts +has(value: T): boolean; +``` + +Tests whether a key is present in the collection. + +##### Parameters + +| Name | Info | +| :---------- | :----------------- | +| **`value`** | The key to lookup. | + +##### Returns + +`true` if the value is in the collection; otherwise, `false`. + +#### clear + +```ts +clear(): void; +``` + +Removes all values from the collection. + +#### delete + +```ts +delete(value: T): boolean; +``` + +Removes a value from the collection. + +##### Parameters + +| Name | Info | +| :---------- | :------------------- | +| **`value`** | The vakue to remove. | + +##### Returns + +`true` if the operation was successful; otherwise, `false`. + +#### forEach + +```ts +forEach( + cb: (this: This, value: T, value2: T, set: this) => void, + thisArg?: This, + ): void; +``` + +Executes a provided function once per each entry in the collection. The callback +is invoked with the current value for both the first and second arguments (to +maintain a similar signature as `forEach` on other iterable objects like `Map` +and `Array`). + +##### Parameters + +| Name | Info | +| :------------ | :------------------------------------------------------ | +| **`cb`** | The callback to execute. | +| **`thisArg`** | The value to use as `this` when executing the callback. | + +##### Returns + +Nothing. + +#### keys + +```ts +keys(): IterableIterator; +``` + +##### Returns + +an Iterable of the values in the collection. + +#### values + +```ts +values(): IterableIterator; +``` + +##### Returns + +an `IterableIterator` for the values present in the collection. + +#### entries + +```ts +entries(): IterableIterator< + [T, T] + >; +``` + +##### Returns + +an `IterableIterator` of the entries present in the collection. Each entry is a +tuple containing the key and value for each element. + +#### [Symbol.iterator] + +```ts +[Symbol.iterator](): IterableIterator< + T + >; +``` + +Returns an iterator of the [`values`](#values "Jump to symbol: 'values'") in the +set. + +--- + +## `SetLikeConstructor` + +Represents a constructor function for a +[`SetLike`](#setlike "Jump to symbol: 'SetLike'") object, which is the base +implementation of a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object, without any of the additional composition methods like `union` or +`intersection`. + +###### See Also + +- [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") for + the full interface with composition methods. +- [`SetLike`](#setlike "Jump to symbol: 'SetLike'") for the core interface + without composition methods. + +### Properties + +#### prototype + +```ts +readonly prototype: SetLike; +``` + +--- diff --git a/docs/set.md b/docs/set.md new file mode 100644 index 0000000..b6cda96 --- /dev/null +++ b/docs/set.md @@ -0,0 +1,43 @@ +# @nick/is/set + +## `isSet` + +#### Signature + +```ts ignore +function isSet(it: unknown): it is Set; +``` + +Checks if a given value is a `Set` instance. This is a more reliable check than +`it instanceof Set` because it also works across different realms. + +It's also more strict than `instanceof` operations, only recognizing an object +as a `Set` instance if it was created with a valid construct operation of either +the `Set` constructor or a subclass of it. As such, +`Object.create(Set.prototype)` and similar avenues will return `false`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Set` instance, `false` otherwise. + +###### Category + +`Keyed Collections` + +#### Examples + +```ts +import { isSet } from "jsr:@nick/is/set"; + +isSet(new Set()); // true +isSet(new WeakSet()); // false +isSet(new Map()); // false +isSet([]); // false +isSet(Object.create(Set.prototype)); // false +``` diff --git a/docs/shared-array-buffer.md b/docs/shared-array-buffer.md new file mode 100644 index 0000000..62eb655 --- /dev/null +++ b/docs/shared-array-buffer.md @@ -0,0 +1,37 @@ +# @nick/is/shared-array-buffer + +## `isSharedArrayBuffer` + +#### Signature + +```ts ignore +function isSharedArrayBuffer(it: unknown): it is SharedArrayBuffer; +``` + +Returns `true` if [`it`](#it "Jump to symbol: 'it'") is a `SharedArrayBuffer`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `SharedArrayBuffer`, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isSharedArrayBuffer } from "jsr:@nick/is/shared-array-buffer"; + +const buffer = new ArrayBuffer(8); +const shared = new SharedArrayBuffer(8); + +isSharedArrayBuffer(buffer); // false +isSharedArrayBuffer(shared); // true +``` diff --git a/docs/string-iterator.md b/docs/string-iterator.md new file mode 100644 index 0000000..1e4f345 --- /dev/null +++ b/docs/string-iterator.md @@ -0,0 +1,62 @@ +# @nick/is/string-iterator + +## `isStringIterator` + +#### Signature + +```ts ignore +function isStringIterator( + it: unknown, +): it is StringIterator; +``` + +Check if the given value is a string iterator, which is an iterable iterator +that yields individual characters from a string literal or String object. This +is the type of object returned by `String.prototype[Symbol.iterator]`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string iterator, `false` otherwise. + +###### Category + +`Iterables` + +#### Examples + +```ts +import { isStringIterator } from "jsr:@nick/is/string-iterator"; + +const str = "foo"; +const iter = str[Symbol.iterator](); +console.log(isStringIterator(iterator)); // true +console.log(isStringIterator(str)); // false +``` + +## `StringIterator` + +Represents a string iterator. + +##### Type Parameters + +- **`T`** extends `string` (default: `string`) + +--- + +##### Extends `IterableIterator[number]>` + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "String Iterator"; +``` + +--- diff --git a/docs/string-object.md b/docs/string-object.md new file mode 100644 index 0000000..0da865d --- /dev/null +++ b/docs/string-object.md @@ -0,0 +1,45 @@ +# @nick/is/string-object + +## `isStringObject` + +#### Signature + +```ts ignore +function isStringObject(it: unknown): it is String; +``` + +Checks if a value is a string object, which is a boxed-primitive string that was +created via the `new String()` constructor, or by wrapping a primitive string in +the `Object()` wrapper function. + +Boxed primitives are strongly discouraged in JavaScript, as they can lead to all +sorts of unexpected behavior and performance issues. As such, this function - +and the other boxed primitive functions like it - are provided for your +convenience, to help you easily ensure your code is not on the receiving end of +such behavior. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string object; otherwise, `false`. + +###### Category + +`Boxed Primitives` + +#### Examples + +```ts +import { isStringObject } from "jsr:@nick/is/string-object"; + +isStringObject(new String("abc")); // true +isStringObject(Object("abc")); // true + +isStringObject("abc"); // false +isStringObject("abc" as unknown); // false +``` diff --git a/docs/string.md b/docs/string.md new file mode 100644 index 0000000..9b6ad21 --- /dev/null +++ b/docs/string.md @@ -0,0 +1,37 @@ +# @nick/is/string + +## `isString` + +#### Signature + +```ts ignore +function isString(it: unknown): it is string; +``` + +Checks if the given value is a string. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isString } from "jsr:@nick/is/string"; + +const x: unknown = "hello"; +if (isString(x)) { + console.log(x.toUpperCase()); + // ^? const x: string +} +``` diff --git a/docs/symbol-object.md b/docs/symbol-object.md new file mode 100644 index 0000000..8f1f456 --- /dev/null +++ b/docs/symbol-object.md @@ -0,0 +1,39 @@ +# @nick/is/symbol-object + +## `isSymbolObject` + +#### Signature + +```ts ignore +function isSymbolObject(it: unknown): it is Symbol; +``` + +Checks if a value is a symbol object, which is a boxed-primitive symbol that was +created by wrapping a primitive symbol in the `Object()` wrapper function. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a boxed-primitive symbol object; otherwise, `false`. + +###### Category + +`Boxed Primitives` + +#### Examples + +```ts +import { isSymbolObject } from "jsr:@nick/is/symbol-object"; + +isSymbolObject(Object(Symbol("abc"))); // true + +isSymbolObject(Symbol("abc")); // false +isSymbolObject(Symbol.iterator); // false +isSymbolObject(Symbol.for("abc")); // false +isSymbolObject("@@abc"); // false +``` diff --git a/docs/symbol.md b/docs/symbol.md new file mode 100644 index 0000000..9c6169a --- /dev/null +++ b/docs/symbol.md @@ -0,0 +1,36 @@ +# @nick/is/symbol + +## `isSymbol` + +#### Signature + +```ts ignore +function isSymbol(it: unknown): it is symbol; +``` + +Check if the given value is a symbol. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a symbol, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isSymbol } from "jsr:@nick/is/symbol"; + +isSymbol(Symbol("foo")); // true +isSymbol(Symbol.iterator); // true +isSymbol(Symbol.for("foo")); // true +isSymbol("@@foo"); // false +``` diff --git a/docs/tagged.md b/docs/tagged.md new file mode 100644 index 0000000..90dc704 --- /dev/null +++ b/docs/tagged.md @@ -0,0 +1,74 @@ +# @nick/is/tagged + +## `isTagged` + +#### Signature + +```ts ignore +function isTagged(it: O): it is O & { + readonly [Symbol.toStringTag]: NormalizeTag; +}; +``` + +Checks if a given value has a `Symbol.toStringTag` property, and optionally +checks if the value of that property matches the given +[tag](#tag "Jump to symbol: 'tag'"). + +##### Parameters + +| Name | Info | +| :-------- | :-------------------------- | +| **`it`** | The value to check. | +| **`tag`** | The value to check against. | + +##### Returns + +`true` if the value has a `Symbol.toStringTag` property that matches the given +[tag](#tag "Jump to symbol: 'tag'") (if provided), otherwise `false`. + +###### Category + +`Objects` + +## `normalizeTag` + +#### Signature + +```ts ignore +function normalizeTag(tag: T): NormalizeTag; +``` + +Normalizes a given toStringTag value, removing any leading and trailing +whitespace and any leading `[object` and trailing `]`, if present. + +## `normalizeTag` + +#### Signature + +```ts ignore +function normalizeTag(tag: string): string; +``` + +## `normalizeTag` + +#### Signature + +```ts ignore +function normalizeTag(tag: string): string; +``` + +## `NormalizeTag` + +#### Signature + +```ts ignore +export type NormalizeTag = Trim< + T extends `[object ${infer U}]` ? U : T +>; +``` + +##### Type Parameters + +- **`T`** extends `string` + +--- diff --git a/docs/template-object.md b/docs/template-object.md new file mode 100644 index 0000000..992d29e --- /dev/null +++ b/docs/template-object.md @@ -0,0 +1,85 @@ +# @nick/is/template-object + +## `isTemplateObject` + +#### Signature + +```ts ignore +function isTemplateObject(it: unknown): it is TemplateObject; +``` + +Checks if the given value is a template strings object, which is an object with +a `raw` property that is an array of strings. + +This type fulfills the requirements of the `String.raw` method without +necessarily being an array of strings, as well. Useful for validating template +literal call sites in tagged template functions, which often times are called +with just a plain object with a `raw` property. + +For a more strict check see +[`isTemplateStringsArray`](#istemplatestringsarray "Jump to symbol: 'isTemplateStringsArray'"), +which checks if the value is _also_ an array of strings. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a template strings object, `false` otherwise. + +###### Category + +`Template Literals` + +#### Examples + +```ts +import { + isTemplateObject, +} from "jsr:@nick/is/template-object"; + +console.log( + isTemplateObject({ raw: ["a", "b", "c"] }) +); // true + +// Additional properties are allowed: +console.log( + isTemplateObject({ raw: ["a", "b", "c"], other: 1 }) +); // true + +// Mimicking a template strings array will pass: +console.log( + isTemplateObject(Object.assign(["\1"], { raw: ["\\1"] }) +); // true + +// However, just having any old `raw` property is not enough: +console.log( + isTemplateObject({ raw: 1 }) +); // false +``` + +## `TemplateObject` + +A template strings object is an object with a `raw` property containing an array +of strings. This type is used to loosely represent the first argument passed to +a tagged template function, which is a template strings array. + +Note: while all `TemplateStringsArray` values are `TemplateObject`s, not all +`TemplateObject`s are `TemplateStringsArray`s. + +###### Category + +`Template Literals` + +### Properties + +#### raw + +```ts +readonly raw: readonly string[]; +``` + +--- diff --git a/docs/template-strings-array.md b/docs/template-strings-array.md new file mode 100644 index 0000000..d32cb81 --- /dev/null +++ b/docs/template-strings-array.md @@ -0,0 +1,87 @@ +# @nick/is/template-strings-array + +## `isTemplateStringsArray` + +#### Signature + +```ts ignore +function isTemplateStringsArray(it: unknown): it is TemplateStringsArray; +``` + +Checks if the given value is a template strings array, which is an array of +strings with an own property named `raw` that also is an array of strings. This +is the type of array provided to tagged template literals for the first +argument, and is represented as the type `TemplateStringsArray` in TypeScript. + +This predicate's type is a supertype of the one checked by its more lenient +counterpart, +[`isTemplateObject`](#istemplateobject "Jump to symbol: 'isTemplateObject'"), +which only checks if the value is an object with a `raw` property that is an +array of strings. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a TemplateStringsArray, `false` otherwise. + +###### Category + +`Template Literals` + +#### Examples + +```ts +import { isTemplateStringsArray } from "jsr:@nick/is/template-strings-array"; + +console.log(isTemplateStringsArray(["a", "b", "c"])); // false +console.log(isTemplateStringsArray({ raw: ["a", "b", "c"] })); // false + +function print(strings: TemplateStringsArray, ...values: any[]): string; +function print(...vals: unknown[]): string; +function print(...vals: unknown[]): string { + const [strings, ...values] = vals; + if (isTemplateStringsArray(strings)) { + return String.raw(strings, ...values); + } else { + return JSON.stringify(vals); + } +} + +print(["a", "b", "c"], 1, 2, 3); // '[["a", "b", "c"], 1, 2, 3]' +print`a${1}b${2}c${3}`; // a1b2c3 +``` + +## `TemplateStringsArray` + +A template strings array is an array of strings with an own property named `raw` +that is also an array of strings. This is the type of array provided to tagged +template literals for the first argument, and is represented as the type +`TemplateStringsArray` in TypeScript. + +Note: while all `TemplateStringsArray` values are `TemplateStringsObject`s, not +all `TemplateStringsObject`s are `TemplateStringsArray`s. + +###### Category + +`Types` + +###### Tags + +`TemplateStringsArray` + +##### Extends `ReadonlyArray` + +### Properties + +#### raw + +```ts +readonly raw: ReadonlyArray; +``` + +--- diff --git a/docs/truthy.md b/docs/truthy.md new file mode 100644 index 0000000..855dee9 --- /dev/null +++ b/docs/truthy.md @@ -0,0 +1,40 @@ +# @nick/is/truthy + +## `isTruthy` + +#### Signature + +```ts ignore +function isTruthy(it: U): it is Exclude; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is truthy, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isTruthy } from "jsr:@nick/is/truthy"; + +isTruthy(1); // true +isTruthy("foo"); // true +isTruthy(true); // true +isTruthy({}); // true + +isTruthy(0); // false +isTruthy(""); // false +isTruthy(false); // false +isTruthy(null); // false +isTruthy(undefined); // false +``` diff --git a/docs/typed-array.md b/docs/typed-array.md new file mode 100644 index 0000000..46272a6 --- /dev/null +++ b/docs/typed-array.md @@ -0,0 +1,432 @@ +# @nick/is/typed-array + +## `isTypedArray` + +#### Signature + +```ts ignore +function isTypedArray( + it: TypedArray | unknowns, +): it is TypedArray; +``` + +Checks if a given value is a typed array, which is a view over a raw binary data +buffer (e.g. `ArrayBuffer`) that provides a fixed-size, typed view into the +buffer. If the [type](#type "Jump to symbol: 'type'") parameter is given, it +checks if the value is that specific typed array type (e.g. `"Uint8Array"` -> +`Uint8Array`). + +For a value to pass this check, it must be an instance of the intrinsic +`%TypedArray%` constructor, and have the `%TypedArrayPrototype%` prototype +inherited by all native typed array types: + +- `Uint8Array` +- `Uint8ClampedArray` +- `Uint16Array` +- `Uint32Array` +- `Int8Array` +- `Int16Array` +- `Int32Array` +- `Float16Array` +- `Float32Array` +- `Float64Array` +- `BigInt64Array` +- `BigUint64Array` + +To check for a specific typed array type, use the `type` parameter or one of the +type-specific checks like `isUint8Array`, etc. + +##### Parameters + +| Name | Info | +| :--------- | :----------------------------------------------------------- | +| **`it`** | The value to check. | +| **`type`** | Name of a specific typed array type to check for (optional). | + +##### Returns + +`true` if the value is a typed array, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isTypedArray } from "jsr:@nick/is/typed-array"; + +const arr = new Uint8Array(8); +isTypedArray(arr); // true +isTypedArray(arr, "Uint8Array"); // true +``` + +## `isTypedArray` + +#### Signature + +```ts ignore +function isTypedArray( + it: unknown, +): it is TypedArray; +``` + +Checks if a given value is a typed array, which is a view over a raw binary data +buffer (e.g. `ArrayBuffer`) that provides a fixed-size, typed view into the +buffer. If the [type](#type "Jump to symbol: 'type'") parameter is given, it +checks if the value is that specific typed array type (e.g. `"Uint8Array"` -> +`Uint8Array`). + +For a value to pass this check, it must be an instance of the intrinsic +`%TypedArray%` constructor, and have the `%TypedArrayPrototype%` prototype +inherited by all native typed array types: + +- `Uint8Array` +- `Uint8ClampedArray` +- `Uint16Array` +- `Uint32Array` +- `Int8Array` +- `Int16Array` +- `Int32Array` +- `Float16Array` +- `Float32Array` +- `Float64Array` +- `BigInt64Array` +- `BigUint64Array` + +To check for a specific typed array type, use the `type` parameter or one of the +type-specific checks like `isUint8Array`, etc. + +##### Parameters + +| Name | Info | +| :--------- | :----------------------------------------------------------- | +| **`it`** | The value to check. | +| **`type`** | Name of a specific typed array type to check for (optional). | + +##### Returns + +`true` if the value is a typed array, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isTypedArray } from "jsr:@nick/is/typed-array"; + +const arr = new Uint8Array(8); +isTypedArray(arr); // true +isTypedArray(arr, "Uint8Array"); // true +``` + +## `isTypedArray` + +#### Signature + +```ts ignore +function isTypedArray( + it: TypedArray | unknowns, + type: K, +): it is TypedArrayTypeMap[K]; +``` + +Checks if a given value is a typed array of a specific +[type](#type "Jump to symbol: 'type'"). The +[type](#type "Jump to symbol: 'type'") parameter must be one of the following +strings: + +- `"Uint8Array"` +- `"Uint8ClampedArray"` +- `"Uint16Array"` +- `"Uint32Array"` +- `"Int8Array"` +- `"Int16Array"` +- `"Int32Array"` +- `"Float16Array"` +- `"Float32Array"` +- `"Float64Array"` +- `"BigInt64Array"` +- `"BigUint64Array"` + +##### Parameters + +| Name | Info | +| :--------- | :------------------------------------------------ | +| **`it`** | The value to check. | +| **`type`** | Name of a specific typed array type to check for. | + +##### Returns + +`true` if the value is a typed array of the specified type, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isTypedArray } from "jsr:@nick/is/typed-array"; + +const arr = new Uint8Array(8); +isTypedArray(arr, "Uint8Array"); // true +isTypedArray(arr, "Uint16Array"); // false +``` + +## `isTypedArray` + +#### Signature + +```ts ignore +function isTypedArray( + it: unknown, + type: K, +): it is TypedArrayTypeMap[K]; +``` + +Checks if a given value is a typed array of a specific +[type](#type "Jump to symbol: 'type'"). The +[type](#type "Jump to symbol: 'type'") parameter must be one of the following +strings: + +- `"Uint8Array"` +- `"Uint8ClampedArray"` +- `"Uint16Array"` +- `"Uint32Array"` +- `"Int8Array"` +- `"Int16Array"` +- `"Int32Array"` +- `"Float16Array"` +- `"Float32Array"` +- `"Float64Array"` +- `"BigInt64Array"` +- `"BigUint64Array"` + +##### Parameters + +| Name | Info | +| :--------- | :------------------------------------------------ | +| **`it`** | The value to check. | +| **`type`** | Name of a specific typed array type to check for. | + +##### Returns + +`true` if the value is a typed array of the specified type, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isTypedArray } from "jsr:@nick/is/typed-array"; + +const arr = new Uint8Array(8); +isTypedArray(arr, "Uint8Array"); // true +isTypedArray(arr, "Uint16Array"); // false +``` + +## `isTypedArray` + +#### Signature + +```ts ignore +function isTypedArray(it: unknown, type?: string): it is TypedArray; +``` + +Checks if a given value is a typed array. + +##### Parameters + +| Name | Info | +| :--------- | :----------------------------------------------------------- | +| **`it`** | The value to check. | +| **`type`** | Name of a specific typed array type to check for (optional). | + +##### Returns + +`true` if the value is a typed array, `false` otherwise. + +###### Category + +`Binary Data Structures` + +## `TypedArray` + +#### Signature + +```ts ignore +export type TypedArray = + InstanceType>; +``` + +Represents an instance of a typed array, which is a view over a raw binary data +buffer (e.g. `ArrayBuffer`) of a fixed-size. The following are the supported +native typed array types: + +- `Uint8Array` +- `Uint8ClampedArray` +- `Uint16Array` +- `Uint32Array` +- `Int8Array` +- `Int16Array` +- `Int32Array` +- `Float16Array` (ES2024) +- `Float32Array` +- `Float64Array` +- `BigInt64Array` +- `BigUint64Array` + +##### Type Parameters + +- **`T`** extends `ArrayBufferLike` (default: `ArrayBufferLike`) + +--- + +###### Category + +`Binary Data Structures` + +###### See Also + +- [isTypedArray](#istypedarray "Jump to symbol: 'isTypedArray'") to check if a + value is this type at runtime. + +## `TypedArrayConstructor` + +#### Signature + +```ts ignore +export type TypedArrayConstructor = + ValueOf>; +``` + +Represents a constructor for typed arrays, which are views over raw binary data +buffers (e.g. `ArrayBuffer`) that provide a fixed-size, typed view into the +buffer. The following are the supported native typed array types: + +- `Uint8Array` +- `Uint8ClampedArray` +- `Uint16Array` +- `Uint32Array` +- `Int8Array` +- `Int16Array` +- `Int32Array` +- `Float16Array` (ES2024) +- `Float32Array` +- `Float64Array` +- `BigInt64Array` +- `BigUint64Array` + +##### Type Parameters + +- **`T`** extends `ArrayBufferLike` (default: `ArrayBufferLike`) + +--- + +## `TypedArrayTypeMap` + +#### Signature + +```ts ignore +export type TypedArrayTypeMap = { + [K in undefined]: InstanceType[K]>; +}; +``` + +Maps the names of TypedArray subclasses to their instance types. This is used to +provide type information to the +[`isTypedArray`](#istypedarray "Jump to symbol: 'isTypedArray'") type guard. + +##### Type Parameters + +- **`T`** extends `ArrayBufferLike` (default: `ArrayBufferLike`) + +--- + +## `TypedArrayTypeName` + +#### Signature + +```ts ignore +export type TypedArrayTypeName = string & keyof TypedArrayTypeMap; +``` + +Represents the name of a `TypedArrayConstructor`, which is a string that +corresponds to a given typed array subclass, e.g. `"Uint8Array"`. + +## `TypedArrayConstructorMap` + +Maps the names of TypedArray subclasses to their constructor types. This is used +to provide type information for the `TypedArray` type and the +[`isTypedArray`](#istypedarray "Jump to symbol: 'isTypedArray'") function. + +##### Type Parameters + +- **`T`** extends `ArrayBufferLike` (default: `ArrayBufferLike`) + +--- + +##### Extends `UnstableTypedArrayConstructorMap` + +### Properties + +#### Uint8Array + +```ts +Uint8Array: typeof Uint8Array; +``` + +#### Uint8ClampedArray + +```ts +Uint8ClampedArray: typeof Uint8ClampedArray; +``` + +#### Uint16Array + +```ts +Uint16Array: typeof Uint16Array; +``` + +#### Uint32Array + +```ts +Uint32Array: typeof Uint32Array; +``` + +#### Int8Array + +```ts +Int8Array: typeof Int8Array; +``` + +#### Int16Array + +```ts +Int16Array: typeof Int16Array; +``` + +#### Int32Array + +```ts +Int32Array: typeof Int32Array; +``` + +#### Float32Array + +```ts +Float32Array: typeof Float32Array; +``` + +#### Float64Array + +```ts +Float64Array: typeof Float64Array; +``` + +--- diff --git a/docs/types.md b/docs/types.md new file mode 100644 index 0000000..13acc2c --- /dev/null +++ b/docs/types.md @@ -0,0 +1,4506 @@ +# @nick/is/types + +## `isWhitespace` + +#### Signature + +```ts ignore +function isWhitespace( + it: S, +): it is IsWhitespace : never>; +``` + +Checks if the provided value is either a string or an iterable of strings that +consists entirely of whitespace characters. + +This function is useful for validating input data, ensuring that it contains +characters other than whitespace. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string or an iterable of strings that consists entirely +of whitespace characters, `false` otherwise. + +###### Category + +`Strings` + +###### Tags + +`whitespace` + +#### Examples + +```ts +import { isWhitespace } from "jsr:@nick/is/whitespace"; + +console.log(isWhitespace(" ")); // true +console.log(isWhitespace("abc")); // false +console.log(isWhitespace(" a ")); // false +console.log(isWhitespace("")); // false +console.log(isWhitespace(" \n\t ")); // true +``` + +## `isWhitespace` + +#### Signature + +```ts ignore +function isWhitespace(it: unknown): it is WhitespaceString; +``` + +## `isWhitespace` + +#### Signature + +```ts ignore +function isWhitespace(it: unknown): it is WhitespaceString; +``` + +## `isWhitespaceChar` + +#### Signature + +```ts ignore +function isWhitespaceChar(it: unknown): it is Whitespace; +``` + +Checks if a given character is a whitespace character. + +This function checks if the provided character is one of the recognized +whitespace characters, including spaces, tabs, newlines, and additional Unicode +whitespace characters. + +##### Parameters + +| Name | Info | +| :------- | :---------------------- | +| **`it`** | The character to check. | + +##### Returns + +`true` if the character is a whitespace character, `false` otherwise. + +###### Category + +`Strings` + +###### Tags + +`whitespace` + +#### Examples + +```ts +import { isWhitespaceChar } from "jsr:@nick/is/whitespace"; + +console.log(isWhitespaceChar(" ")); // true +console.log(isWhitespaceChar("\n")); // true +console.log(isWhitespaceChar("\t")); // true +console.log(isWhitespaceChar("a")); // false +``` + +## `isWhitespaceCode` + +#### Signature + +```ts ignore +function isWhitespaceCode(it: unknown): it is WhitespaceCode; +``` + +Checks if a given value is a whitespace character code. + +This function checks if the provided value is a number and if it is included in +the list of recognized whitespace character codes, which is exposed as the +[`WHITESPACE\_CODES`](#whitespace-codes "Jump to symbol: 'WHITESPACE_CODES'") +array. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a whitespace character code, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike( + it: S, +): it is IsWhitespace; +``` + +Checks if the provided value is either a string or an iterable of strings that +consists entirely of whitespace characters. + +This function is useful for validating input data, ensuring that it contains +characters other than whitespace. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string or an iterable of strings that consists entirely +of whitespace characters, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike( + it: N, +): it is IsWhitespaceCode; +``` + +Checks if the provided value is a whitespace character code. + +This function checks if the provided value is a number and if it is included in +the list of recognized whitespace character codes, which is exposed as the +[`WHITESPACE\_CODES`](#whitespace-codes "Jump to symbol: 'WHITESPACE_CODES'") +array. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a whitespace character code, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike(it: Iterable): it is Iterable; +``` + +Checks if the provided value is either a string or an iterable of strings that +consists entirely of whitespace characters. + +This function is useful for validating input data, ensuring that it contains +characters other than whitespace. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string or an iterable of strings that consists entirely +of whitespace characters, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike(it: number): it is WhitespaceCode; +``` + +Checks if the provided value is a whitespace character code. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a whitespace character code, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike(it: unknown): it is WhitespaceLike; +``` + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike( + it: unknown, +): it is string | WhitespaceCode | Iterable; +``` + +## `ArrayBufferLike` + +#### Signature + +```ts ignore +export type ArrayBufferLike = ArrayBuffer | SharedArrayBuffer; +``` + +Represents an "ArrayBuffer-like" value, which is either an `ArrayBuffer` or +`SharedArrayBuffer` instance. + +###### Category + +`Binary Data Structures` + +## `ArrayLikeObject` + +#### Signature + +```ts ignore +export type ArrayLikeObject = ArrayLike & object; +``` + +Represents an object that has a `length` property that is a finite unsigned +integer, and where the object is not a function. This is the type that the +function +[`isArrayLikeObject`](#isarraylikeobject "Jump to symbol: 'isArrayLikeObject'") +narrows its inputs to. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +###### Category + +`Indexed Collections` + +## `AsyncIterableObject` + +#### Signature + +```ts ignore +export type AsyncIterableObject = AsyncIterable & object; +``` + +An object that implements the `AsyncIterable` interface. This is the type that +the +[isAsyncIterableObject](#isasynciterableobject "Jump to symbol: 'isAsyncIterableObject'") +function checks for and (narrows to). + +##### Type Parameters + +- **`T`** + +--- + +###### Category + +`Iterables` + +## `BigInteger` + +#### Signature + +```ts ignore +export type BigInteger = CastInt; +``` + +Casts a value into a big integer type (which is really just a bigint). If the +value is not a bigint or a string containing a valid integer, it will resolve to +`never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `Cast` + +#### Signature + +```ts ignore +export type Cast = Extract & T; +``` + +Casts a value into a specific numeric type. If the value is not a number, it +will resolve to `never`, indicating its incompatibility with the type. + +This is a low-level utility type that primarily serves as an internal helper for +more user-friendly types like [Integer](#integer "Jump to symbol: 'Integer'") +and [Positive](#positive "Jump to symbol: 'Positive'"). Unless you're building +custom numeric types with your own branding, you most likely never directly +handle this type in the wild. + +##### Type Parameters + +- **`N`** +- **`T`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { Cast } from "jsr:@nick/is/number"; + +declare const MY_DOUBLE: unique symbol; +type DOUBLE = Cast; + +let x = 4.3210123210 as DOUBLE; +let y = 3.1415926535 as DOUBLE; + +console.log(x + y); // 7.4626049745 + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'DOUBLE'. +``` + +## `CastInt` + +#### Signature + +```ts ignore +export type CastInt = Extract & T; +``` + +Casts a value into a specific integer type. If the value is not a bigint, it +will resolve to `never`, indicating its incompatibility with the type. + +This is a low-level utility type that primarily serves as an internal helper for +more user-friendly types like +[BigInteger](#biginteger "Jump to symbol: 'BigInteger'") or +[PositiveBigInteger](#positivebiginteger "Jump to symbol: 'PositiveBigInteger'"). +Unless you're building custom numeric types with your own branding, you most +likely will never directly handle this type in the wild. + +##### Type Parameters + +- **`N`** +- **`T`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { CastInt } from "jsr:@nick/is/number"; + +declare const INTEGER: unique symbol; +type INTEGER = CastInt; + +let x = 3n as INTEGER; +let y = 5n as INTEGER; + +console.log(x + y); // 8n +``` + +## `DateString` + +#### Signature + +```ts ignore +export type DateString = string & IsDateString; +``` + +Represents a valid date string that can be parsed by the native `Date` +constructor without any additional formatting or help from external tools. + +This is a branded nominal type that can be used to strictly distinguish between +regular strings and those that have been validated as date strings through a +runtime check like +[`isDateString`](#isdatestring "Jump to symbol: 'isDateString'"). + +Combined with the aforementioned type guard, this type allows you to enforce the +validity of date strings both at runtime and compile time. If your users are not +exposed to this type alias, the only way a value of this type can be created is +by satisfying the `isDateString` function check. + +###### Category + +`Types` + +###### Tags + +`date-string` `nominal` + +## `Enum` + +#### Signature + +```ts ignore +export type Enum = EnumLike & T; +``` + +Represents a TypeScript `enum` object, which is defined as a plain object that +satisfies one of the following conditions: + +- String or numeric keys mapped to string or numeric values. +- Values can be constant or computed. + +> Declared keys may only be literal static strings. Numeric keys are not allowed +> in the declaration of an enum. The only legal way to create an enum with +> numeric keys like `"0"` is for the compiler to generate them. + +String-to-string enums **may not** have reverse mappings. It is only supported +for constant numeric values (whether explicitly specified via initializers, or +implicitly assigned by the TS compiler). + +> When defined with the `enum` keyword and constant numeric values (or no +> explicit values specified at all, which defaults to `0` for the first key and +> increments by `1` for each subsequent key), the TypeScript compiler +> auto-generates an implicit reverse-mapping from the values back to their +> respective keys. + +##### Type Parameters + +- **`T`** extends `EnumLike` (default: `EnumLike`) + +--- + +#### Examples + +Constant enum definition + +```ts +enum Abc { + B = 0, + C = 1, +} +``` + +Mixed-value enum definition (no reverse mapping) + +```ts +// Mixing string and numeric values in an enum definition will +// prevent the compiler from generating reverse mappings (since +// it only generates such mappings for constant numeric values). +enum Abc { + B = 0, + C = "c", +} +``` + +Constant enum definition (implicit value assignment) + +```ts +// auto-generates a reverse mapping from 0 => B and 1 => C +enum Abc { + B, // = 0 + C, // = 1 + // "0" = "B", + // "1" = "C", +} +``` + +Computed enum definition + +```ts +enum C { + D = "e" + "f", // "ef" +} +``` + +## `Even` + +#### Signature + +```ts ignore +export type Even = Cast; +``` + +Branded type representing an even number or bigint. Used by overloads of the +[`isEven`](#iseven "Jump to symbol: 'isEven'") function to differentiate between +odd and even numbers. + +##### Type Parameters + +- **`T`** extends `Numeric` (default: `Numeric`) + +--- + +###### Category + +`Numeric` + +## `Exclusivity` + +#### Signature + +```ts ignore +export type Exclusivity = AnyRange[2]; +``` + +## `Falsy` + +#### Signature + +```ts ignore +export type Falsy = null | undefined | void | false | 0 | 0n | "" | NaN; +``` + +A type that represents all falsy values. + +###### Category + +`Primitives` + +## `Finite` + +#### Signature + +```ts ignore +export type Finite = Cast; +``` + +Casts a value into a finite type. If the value is not a number, it will resolve +to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `Float` + +#### Signature + +```ts ignore +export type Float = Cast; +``` + +Casts a value into a floating-point type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float` `number` + +#### Examples + +```ts +import { type Float, isFloat } from "@nick/is/float"; + +let x = 1.5 as Float, y = 0; + +if (isFloat(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float'. +``` + +## `Float16` + +#### Signature + +```ts ignore +export type Float16 = Cast; +``` + +Casts a value into a 16-bit floating-point type (half-precision). + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float16` `number` + +#### Examples + +```ts +import { type Float16, isFloat16 } from "@nick/is/float16"; + +let i = 1.5 as Float16, y = 0; + +if (isFloat16(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = 1; // <- TS2322 Type '1' is not assignable to type 'Float16'. +``` + +## `Float32` + +#### Signature + +```ts ignore +export type Float32 = Cast; +``` + +Casts a value into a floating-point type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float32` `number` + +#### Examples + +```ts +import { type Float32, isFloat32 } from "@nick/is/float32"; + +let x = 1.5 as Float32, y = 0; + +if (isFloat32(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float32'. +``` + +## `Float64` + +#### Signature + +```ts ignore +export type Float64 = Cast; +``` + +Casts a value into a float64-precision floating-point type. If the value is not +a number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float64` `number` + +#### Examples + +```ts +import { type Float64, isFloat64 } from "jsr:@type/number/float64"; + +let x = 1.5 as Float64, y = 0; + +if (isFloat64(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float64'. +``` + +## `Identifier` + +#### Signature + +```ts ignore +export type Identifier = Brand; +``` + +Utility type brand that represents a valid JavaScript identifier. This is a +string that can be used as a name of a variable, function, property, label, or +export. It is a subtype of `string` and is used to distinguish between regular +strings and identifiers. + +##### Type Parameters + +- **`T`** extends `string` (default: `string`) + +--- + +###### Category + +`Primitives` + +## `Infinity` + +#### Signature + +```ts ignore +export type Infinity = PositiveInfinity | NegativeInfinity; +``` + +Special type representing either positive or negative infinity. + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` + +## `InRange` + +#### Signature + +```ts ignore +export type InRange< + N extends number, + Min extends number = number, + Max extends number = number, + Tex extends Exclusivity = Exclusivity, +> = + & (number extends N ? IsInRange + : `${Min}|${Max}` extends `-${number}|-${number}` + ? `${N}` extends `-${number}` ? IsInRange : never + : `${Min}|${Max}` extends `${number}|-${number}` ? never + : `${Min}|${Max}` extends `-${number}|${number}` + ? `${N}` extends `-${number}` ? IsInRange : never + : `${N}` extends `-${number}` ? never + : IsInRange) + & N; +``` + +Type-level equivalent to the [`inRange`](#inrange "Jump to symbol: 'inRange'") +function, which (naively) checks if a number is within a given range. The range +can be specified in multiple ways, with one of four different exclusivity types. + +##### Type Parameters + +- **`N`** extends `number` +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `Exclusivity`) + +--- + +###### See Also + +- [`inRange`](#inrange "Jump to symbol: 'inRange'") for more information. + +## `Int16` + +#### Signature + +```ts ignore +export type Int16 = Cast; +``` + +Casts a value into a signed 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/int16"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -32769; // <- TS2322 Type '-32769' is not assignable to type 'Int16'. +``` + +## `Int32` + +#### Signature + +```ts ignore +export type Int32 = Cast; +``` + +Casts a value into a signed 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int32` `number` + +#### Examples + +```ts +import { type Int32, isInt32 } from "jsr:@type/number/int32"; + +let value = 1 as Int32; + +const setValue = (newValue: Int32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -2147483649; // <- TS2322 Type '-2147483649' is not assignable to type 'Int32'. +``` + +## `Int8` + +#### Signature + +```ts ignore +export type Int8 = Cast; +``` + +Casts a value into a signed 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int8` `number` + +#### Examples + +```ts +import { type Int8, isInt8 } from "@nick/is/int8"; + +let i = 1 as Int8, y = 0; + +if (isInt8(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = 1.5; // <- TS2322 Type '1.5' is not assignable to type 'Int8'. +``` + +## `Integer` + +#### Signature + +```ts ignore +export type Integer = N extends bigint + ? `${N}` extends `${infer I extends number}` ? N & Integer : never + : N extends number + ? number extends N ? N & INTEGER + : `${N}` extends `${bigint}` ? N & INTEGER : never + : never; +``` + +Casts a value into an integer type. If the value is not an number, or is a +non-integral number like 3.14, it will resolve to `never`. + +**Note**: once a value is cast to a type with this narrow of a constraint, +TypeScript's compiler will refuse any assignment to it that is not _exactly_ +compatible with the type. If you find yourself encountering errors about +incompatible types, try using the +[MaybeInteger](#maybeinteger "Jump to symbol: 'MaybeInteger'") type instead. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { type Integer, isInteger } from "jsr:@type/number"; + +function add(a: Integer, b: Integer) { + return (a + b) as Integer; +} + +let x = 1 as Integer, y = 2 as Integer, z = 3; + +if (isInteger(z)) { + console.log(add(add(x, y), z)); +} else { + console.log(add(x, y)); +} + +// These will raise TypeScript compiler errors: +add(x, z); +add(y, 3); + +// This level of strictness can be a bit silly in the wrong application: +x = 1; // <- TS4321 (`MaybeInteger` would be a better choice here) +``` + +## `IsEven` + +#### Signature + +```ts ignore +export type IsEven = `${T}` extends + `${"" | bigint}${1 | 3 | 5 | 7 | 9}` ? True : False; +``` + +Type-level equivalent of [`isEven`](#iseven "Jump to symbol: 'isEven'"), which +checks if a given numeric type (number or bigint) ends in an even number. +Returns [True](#true "Jump to symbol: 'True'") if so, and +[False](#false "Jump to symbol: 'False'") otherwise. + +##### Type Parameters + +- **`T`** extends `Numeric` +- **`True`** (default: `T`) +- **`False`** (default: `never`) + +--- + +###### Category + +`Numeric` + +## `IsOdd` + +#### Signature + +```ts ignore +export type IsOdd = + `${number}` extends `${T}` ? True + : `${bigint}` extends `${T}` ? True + : `${T}` extends `${infer _}${1 | 3 | 5 | 7 | 9}` ? True + : False; +``` + +Type-level equivalent of [`isOdd`](#isodd "Jump to symbol: 'isOdd'"), which +checks if a given numeric type (number or bigint) ends in an odd number. Returns +[True](#true "Jump to symbol: 'True'") if so, and +[False](#false "Jump to symbol: 'False'") otherwise. + +##### Type Parameters + +- **`T`** extends `Numeric` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Numeric` + +## `IsWhitespace` + +#### Signature + +```ts ignore +export type IsWhitespace = + IsNever extends true ? False + : IsAny extends true ? True : T extends Whitespace ? True + : T extends `${Whitespace}${infer R}` ? IsWhitespace + : False; +``` + +If the given string [`T`](#t "Jump to symbol: 'T'") is whitespace, this type +will resolve to the [`True`](#true "Jump to symbol: 'True'") type parameter +(default: `true`). Otherwise, it will resolve to the +[`False`](#false "Jump to symbol: 'False'") type parameter (default: `false`). + +##### Type Parameters + +- **`T`** extends `string` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +###### Tags + +`whitespace` + +## `IsWhitespaceChar` + +#### Signature + +```ts ignore +export type IsWhitespaceChar = + T extends Whitespace ? True : False; +``` + +Type-level predicate that checks if a given string +[`T`](#t "Jump to symbol: 'T'") is a whitespace character. If +[`T`](#t "Jump to symbol: 'T'") is a whitespace character, it will resolve to +the [`True`](#true "Jump to symbol: 'True'") type parameter (default: `true`). +Otherwise, it will resolve to the [`False`](#false "Jump to symbol: 'False'") +type parameter (default: `false`). + +The compile-time equivalent of the +[`isWhitespaceChar`](#iswhitespacechar "Jump to symbol: 'isWhitespaceChar'") +function. + +##### Type Parameters + +- **`T`** extends `string` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +## `IsWhitespaceCode` + +#### Signature + +```ts ignore +export type IsWhitespaceCode = + T extends WhitespaceCode ? True : False; +``` + +Type-level predicate that checks if a given string +[`T`](#t "Jump to symbol: 'T'") is a whitespace character code. If +[`T`](#t "Jump to symbol: 'T'") is a whitespace character code, it will resolve +to the [`True`](#true "Jump to symbol: 'True'") type parameter (default: +`true`). Otherwise, it will resolve to the +[`False`](#false "Jump to symbol: 'False'") type parameter (default: `false`). + +The compile-time equivalent of the +[`isWhitespaceCode`](#iswhitespacecode "Jump to symbol: 'isWhitespaceCode'") +function. + +##### Type Parameters + +- **`T`** extends `number` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +## `IterableObject` + +#### Signature + +```ts ignore +export type IterableObject = Iterable & object; +``` + +Represents an object that is also an iterable. This is the type of arrays, maps, +sets, and objects with a Symbol.iterator method. It is a subtype of both +`Iterable` and `object`. This is also the type that the function +[isIterableObject](#isiterableobject "Jump to symbol: 'isIterableObject'") +narrows its inputs to. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +###### Category + +`Iterables` + +## `MaybeFinite` + +#### Signature + +```ts ignore +export type MaybeFinite = Cast; +``` + +Casts a value into a partial finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeFloat16` + +#### Signature + +```ts ignore +export type MaybeFloat16 = Cast; +``` + +Casts a value into a partial 16-bit floating-point type (half-precision). + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float16` `number` + +## `MaybeFloat32` + +#### Signature + +```ts ignore +export type MaybeFloat32 = Cast; +``` + +Casts a value into a partial floating-point type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float32` `number` + +#### Examples + +```ts +import { isFloat32, type MaybeFloat32 } from "@nick/is/float32"; + +let x = 1.5 as MaybeFloat32, y = 0; + +if (isFloat32(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Float32`) +``` + +## `MaybeFloat64` + +#### Signature + +```ts ignore +export type MaybeFloat64 = Cast; +``` + +Casts a value into a partial float64-precision floating-point type. If the value +is not a number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float64` `number` + +#### Examples + +```ts +import { isFloat64, type MaybeFloat64 } from "jsr:@type/number/float64"; + +let x = 1.5 as MaybeFloat64, y = 0; + +if (isFloat64(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Float64`) +``` + +## `MaybeInt16` + +#### Signature + +```ts ignore +export type MaybeInt16 = Cast; +``` + +Casts a value into a partial signed 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/int16"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +value = -32769; // Error: Type '-32769' is not assignable to type 'Int16'. +``` + +## `MaybeInt32` + +#### Signature + +```ts ignore +export type MaybeInt32 = Cast; +``` + +Casts a value into a partial signed 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int32` `number` + +#### Examples + +```ts +import { isInt32, type MaybeInt32 } from "jsr:@type/number/int32"; + +let value = 1 as MaybeInt32; + +const setValue = (newValue: MaybeInt32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! +value = -2147483649; // <- No error! (this is the main difference from `Int32`) +``` + +## `MaybeInt8` + +#### Signature + +```ts ignore +export type MaybeInt8 = Cast; +``` + +Casts a value into a partial signed 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int8` `number` + +#### Examples + +```ts +import { isInt8, type MaybeInt8 } from "@nick/is/int8"; + +let i = 1 as MaybeInt8, y = 0; + +if (isInt8(i)) { + console.log(i); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Int8`) +``` + +## `MaybeInteger` + +#### Signature + +```ts ignore +export type MaybeInteger = N extends bigint + ? `${N}` extends `${infer I extends number}` ? N & MaybeInteger : never + : N extends number + ? number extends N ? N & MAYBE_INTEGER + : `${N}` extends `${bigint}` ? N & MAYBE_INTEGER + : never + : never; +``` + +Casts a value into a partial integer type. If the value is not an number, or is +a non-integral number like 3.14, it will resolve to `never`. This type is nearly +identical to [Integer](#integer "Jump to symbol: 'Integer'"), except it allows +assignment of values that are not precisely compatible with the type, while +still providing an extra level of type safety over the base `number` type. + +Once a value is cast to a type of this constraint, TypeScript's compiler will +refuse any incompatible assignment to it. To demonstrate, consider this example: + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { + isInteger, + type MaybeFloat, + type MaybeInteger, +} from "jsr:@type/number"; + +function add(a: MaybeInteger, b: MaybeInteger) { + return (a + b) as MaybeInteger; +} + +let x = 1 as MaybeInteger, y = 2 as MaybeInteger, z = 3; +let xx = 1.1 as MaybeFloat, yy = 2.2 as MaybeFloat, zz = 3.3; + +if (isInteger(z)) { + console.log(add(add(x, y), z)); +} else { + console.log(add(x, y)); +} + +// These will raise TypeScript compiler errors: +add(x, yy); // <- TS2345 Type 'MaybeFloat' is not assignable to type 'MaybeInteger'. +y = yy; // <- TS2322 Type 'MaybeFloat' is not assignable to type 'MaybeInteger'. + +y = 2; // <- No error! (this is the main difference from `Integer`) +``` + +## `MaybeNegative` + +#### Signature + +```ts ignore +export type MaybeNegative = Cast; +``` + +Casts a value into a partial negative type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Types` `Numbers` + +###### Tags + +`maybe` `negative` `number` + +#### Examples + +```ts +import { isNegative, type MaybeNegative } from "jsr:@type/number"; + +let x = -1 as MaybeNegative, y = 0; + +if (isNegative(x)) { + console.log(x); +} else { + console.log(y); +} + +y = -1; // <- No error! (this is the main difference from `Negative`) +``` + +## `MaybeNegativeFinite` + +#### Signature + +```ts ignore +export type MaybeNegativeFinite = Cast; +``` + +Casts a value into a partial negative finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeNegativeNonZero` + +#### Signature + +```ts ignore +export type MaybeNegativeNonZero = Cast< + N, + MAYBE_NEGATIVE & MAYBE_NON_ZERO +>; +``` + +Casts a value into a partial negative nonzero type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeNegativeNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybeNegativeNonZeroFinite = Cast< + N, + MAYBE_NEGATIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a partial negative nonzero finite type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeNegativeZero` + +#### Signature + +```ts ignore +export type MaybeNegativeZero = Cast; +``` + +Casts a value into a partial negative zero type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero, type MaybeNegativeZero } from "jsr:@type/number"; + +let x = -0 as MaybeNegativeZero, y = 0; + +if (isNegativeZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = -0; // <- No error! (this is the main difference from `NegativeZero`) +``` + +## `MaybeNonZero` + +#### Signature + +```ts ignore +export type MaybeNonZero = Cast; +``` + +Casts a value into a partial nonzero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero, type MaybeNonZero } from "jsr:@type/number"; + +let x = 1 as MaybeNonZero, y = 0; + +if (isNonZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `NonZero`) +``` + +## `MaybeNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybeNonZeroFinite = Cast; +``` + +Casts a value into a partial nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +## `MaybePositive` + +#### Signature + +```ts ignore +export type MaybePositive = Cast; +``` + +Casts a value into a partial positive type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `positive` `number` + +#### Examples + +```ts +import { isPositive, type MaybePositive } from "jsr:@type/number"; + +let x = 1 as MaybePositive, y = 0; + +if (isPositive(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Positive`) +``` + +## `MaybePositiveFinite` + +#### Signature + +```ts ignore +export type MaybePositiveFinite = Cast; +``` + +Casts a value into a partial positive finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybePositiveNonZero` + +#### Signature + +```ts ignore +export type MaybePositiveNonZero = Cast< + N, + MAYBE_POSITIVE & MAYBE_NON_ZERO +>; +``` + +Casts a value into a partial positive nonzero type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybePositiveNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybePositiveNonZeroFinite = Cast< + N, + MAYBE_POSITIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a partial positive nonzero finite type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybePositiveZero` + +#### Signature + +```ts ignore +export type MaybePositiveZero = Cast; +``` + +Casts a value into a partial positive zero type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero, type MaybePositiveZero } from "jsr:@type/number"; + +let x = 0 as MaybePositiveZero, y = 1; + +if (isPositiveZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 0; // <- No error! (this is the main difference from `PositiveZero`) +``` + +## `MaybeUint16` + +#### Signature + +```ts ignore +export type MaybeUint16 = Cast; +``` + +Casts a value into a partial unsigned 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `MaybeUint32` + +#### Signature + +```ts ignore +export type MaybeUint32 = Cast; +``` + +Casts a value into a partial unsigned 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `MaybeUint8` + +#### Signature + +```ts ignore +export type MaybeUint8 = Cast; +``` + +Casts a value into a partial unsigned 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint8, type MaybeUint8 } from "@nick/is/uint8"; + +let i = 1 as MaybeUint8, y = 0; + +if (isUint8(i)) { + console.log(i); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Uint8`) +``` + +## `MaybeZero` + +#### Signature + +```ts ignore +export type MaybeZero = Cast; +``` + +Casts a value into a partial zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isZero, type MaybeZero } from "jsr:@type/number"; + +let x = 0 as MaybeZero, y = 1; + +if (isZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 0; // <- No error! (this is the main difference from `Zero`) +``` + +## `NaN` + +#### Signature + +```ts ignore +export type NaN = Cast; +``` + +Casts a value into a branded type that represents the special numeric value +`NaN` (not a number). This is a very strict type, and it prevents any other type +from being assigned unless they pass the +[`isNaN`](#isnan "Jump to symbol: 'isNaN'") type guard. If the value is not a +subtype of `number`, this will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNan, type NaN } from "jsr:@type/number"; + +let x = NaN as NaN, y = 0; + +if (isNan(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NaN'. +``` + +## `Negative` + +#### Signature + +```ts ignore +export type Negative = Cast; +``` + +Casts a value into a negative type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`negative` `number` + +#### Examples + +```ts +import { isNegative, type Negative } from "jsr:@type/number"; + +let x = -1 as Negative, y = 0; + +if (isNegative(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'Negative'. +``` + +## `NegativeBigInteger` + +#### Signature + +```ts ignore +export type NegativeBigInteger = CastInt; +``` + +Casts a value into a negative big integer type. If the value is not a bigint or +a string containing a valid integer, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `NegativeFinite` + +#### Signature + +```ts ignore +export type NegativeFinite = Cast; +``` + +Casts a value into a negative finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeFiniteInteger` + +#### Signature + +```ts ignore +export type NegativeFiniteInteger = Cast< + N, + NEGATIVE & FINITE & INTEGER +>; +``` + +Casts a value into a negative finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeInfinity` + +#### Signature + +```ts ignore +export type NegativeInfinity = -Infinity; +``` + +Special type representing negative infinity (`Number.NEGATIVE_INFINITY`). + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` `negative` + +## `NegativeInteger` + +#### Signature + +```ts ignore +export type NegativeInteger = Cast; +``` + +Casts a value into a negative integer type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZero` + +#### Signature + +```ts ignore +export type NegativeNonZero = Cast; +``` + +Casts a value into a negative nonzero type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZeroFinite` + +#### Signature + +```ts ignore +export type NegativeNonZeroFinite = Cast< + N, + NEGATIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a negative nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type NegativeNonZeroFiniteInteger = Cast< + N, + NEGATIVE & NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a negative nonzero finite integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZeroInteger` + +#### Signature + +```ts ignore +export type NegativeNonZeroInteger = Cast< + N, + NEGATIVE & NON_ZERO & INTEGER +>; +``` + +Casts a value into a negative nonzero integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeZero` + +#### Signature + +```ts ignore +export type NegativeZero = Cast; +``` + +Casts a value into a negative zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero, type NegativeZero } from "jsr:@type/number"; + +let x = -0 as NegativeZero, y = 0; + +if (isNegativeZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NegativeZero'. +``` + +## `NonEmptyArray` + +#### Signature + +```ts ignore +export type NonEmptyArray = [T, ...T[]]; +``` + +Represents an array with 1 or more element of the specific type `T`. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +###### Category + +`Indexed Collections` + +## `NonZero` + +#### Signature + +```ts ignore +export type NonZero = Cast; +``` + +Casts a value into a nonzero type. If the value is not a number, it will resolve +to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero, type NonZero } from "jsr:@type/number"; + +let x = 1 as NonZero, y = 0; + +if (isNonZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NonZero'. +``` + +## `NonZeroFinite` + +#### Signature + +```ts ignore +export type NonZeroFinite = Cast; +``` + +Casts a value into a nonzero finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type NonZeroFiniteInteger = Cast< + N, + NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a nonzero finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NonZeroInteger` + +#### Signature + +```ts ignore +export type NonZeroInteger = Cast; +``` + +Casts a value into a nonzero integer type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `Odd` + +#### Signature + +```ts ignore +export type Odd = Cast< + IsOdd, Extract, never>, + ODD +>; +``` + +Branded type representing an odd number. Used by overloads of the +[`isOdd`](#isodd "Jump to symbol: 'isOdd'") function to differentiate between +odd and even numbers. + +##### Type Parameters + +- **`T`** (default: `number`) + +--- + +###### Category + +`Numeric` + +## `Positive` + +#### Signature + +```ts ignore +export type Positive = Cast; +``` + +Casts a value into a positive type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive, type Positive } from "jsr:@type/number"; + +let x = 1 as Positive, y = 0; + +if (isPositive(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'Positive'. +``` + +## `PositiveBigInteger` + +#### Signature + +```ts ignore +export type PositiveBigInteger = CastInt; +``` + +Casts a value into a positive big integer type. If the value is not a bigint or +a string containing a valid integer, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `PositiveFinite` + +#### Signature + +```ts ignore +export type PositiveFinite = Cast; +``` + +Casts a value into a positive finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveFiniteInteger` + +#### Signature + +```ts ignore +export type PositiveFiniteInteger = Cast< + N, + POSITIVE & FINITE & INTEGER +>; +``` + +Casts a value into a positive finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveInfinity` + +#### Signature + +```ts ignore +export type PositiveInfinity = Infinity; +``` + +Special type representing positive infinity (`Number.POSITIVE_INFINITY`). + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` `positive` + +## `PositiveInteger` + +#### Signature + +```ts ignore +export type PositiveInteger = Cast; +``` + +Casts a value into a positive finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZero` + +#### Signature + +```ts ignore +export type PositiveNonZero = Cast; +``` + +Casts a value into a positive nonzero type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZeroFinite` + +#### Signature + +```ts ignore +export type PositiveNonZeroFinite = Cast< + N, + POSITIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a positive nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type PositiveNonZeroFiniteInteger = Cast< + N, + POSITIVE & NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a positive nonzero finite integer type. If the value is not a +number, it will resolve to `never`.s + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZeroInteger` + +#### Signature + +```ts ignore +export type PositiveNonZeroInteger = Cast< + N, + POSITIVE & NON_ZERO & INTEGER +>; +``` + +Casts a value into a positive nonzero integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveZero` + +#### Signature + +```ts ignore +export type PositiveZero = Cast; +``` + +Casts a value into a positive zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero, type PositiveZero } from "jsr:@type/number"; + +let x = 0 as PositiveZero, y = 1; + +if (isPositiveZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'PositiveZero'. +``` + +## `Primitive` + +#### Signature + +```ts ignore +export type Primitive = + | string + | number + | bigint + | boolean + | symbol + | null + | undefined; +``` + +Represents a primitive value. This includes strings, numbers, bigints, booleans, +symbols, null, and undefined. + +###### Category + +`Primitives` + +## `Printable` + +#### Signature + +```ts ignore +export type Printable = string | number | bigint | boolean | null | undefined; +``` + +Represents a value that can be printed in a template literal type string, which +means it is either a `string`, `number`, `bigint`, `boolean`, `null` or +`undefined`. Any other type of value will raise a compiler error if you attempt +to construct a template literal type with it. + +#### Examples + +```ts +import type { Printable } from "jsr:@nick/is/printable"; + +type Join = T extends + [infer F extends Printable, ...infer R] + ? `${F}${R extends [] ? "" : D}${Join}` + : ""; + +type Result = Join<[1, "two", 3n, true, null, undefined]>; +// ^? type Result = "1two3true" +``` + +## `Range` + +#### Signature + +```ts ignore +export type Range< + Min extends number = number, + Max extends number = number, + Tex extends Exclusivity = never, +> = [Tex] extends [never] + ? + | RangeInclusiveMin + | RangeInclusive + | RangeInclusiveMax + | RangeExclusive + | RangeUnknown + : Either< + Extract, Required>>, + RangeUnknown + >; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `never`) + +--- + +## `RegisteredSymbol` + +#### Signature + +```ts ignore +export type RegisteredSymbol = Brand; +``` + +Branded type representing a symbol that is registered in the global symbol +registry, which means it was created using the `Symbol.for()` function. This +kind of symbol is **not** allowed as keys in Weak Collections like `WeakMap` or +`WeakSet` objects, as they are not truly unique. + +This is the type that the +[`isRegisteredSymbol`](#isregisteredsymbol "Jump to symbol: 'isRegisteredSymbol'") +type guard narrows its input values to. It is provided as an export for you to +use in tandem with that type guard, to ensure your code is handling registered +symbols in a strict, type-safe manner. + +###### Categories + +`Primitives` `Types` + +#### Examples + +```ts +import { + isRegisteredSymbol, + type RegisteredSymbol, +} from "jsr:@nick/is/registered-symbol"; + +function doSomething(key: RegisteredSymbol): void { + // ... +} + +const key = Symbol.for("foo"); +if (isRegisteredSymbol(key)) { + doSomething(key); +} +``` + +```ts +import { + isRegisteredSymbol, + type RegisteredSymbol, +} from "jsr:@nick/is/registered-symbol"; + +function assertRegisteredSymbol( + value: unknown, +): asserts value is RegisteredSymbol { + if (!isRegisteredSymbol(value)) { + throw new Error("Expected a registered symbol."); + } +} +``` + +## `SemVer` + +#### Signature + +```ts ignore +export type SemVer = Brand; +``` + +Represents a validated Semantic Version (SemVer v2.0.0) string. This is the type +the [`isSemVer`](#issemver "Jump to symbol: 'isSemVer'") function narrows its +input values to. + +###### Category + +`Strings` + +## `SupportedSetLike` + +#### Signature + +```ts ignore +export type SupportedSetLike = + Exclude, keyof SetLike> extends + keyof globalThis.Set ? ExtendedSetLike : SetLike; +``` + +This type represents either the full +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +interface, or the [`SetLike`](#setlike "Jump to symbol: 'SetLike'") interface, +depending on whether the current environment supports composition methods +introduced by the TC39 Set Methods Proposal. + +If the current environment supports the composition methods, this type will +resolve to the +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +interface. Otherwise, it will resolve to the +[`SetLike`](#setlike "Jump to symbol: 'SetLike'") interface. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +###### See Also + +- [`SupportedSetLikeConstructor`](#supportedsetlikeconstructor "Jump to symbol: 'SupportedSetLikeConstructor'") + for a similar type that represents the constructor function for the supported + set-like object. + +## `SupportedSetLikeConstructor` + +#### Signature + +```ts ignore +export type SupportedSetLikeConstructor = + Exclude extends + keyof globalThis.SetConstructor ? ExtendedSetLikeConstructor + : SetLikeConstructor; +``` + +This type represents either the full +[`ExtendedSetLikeConstructor`](#extendedsetlikeconstructor "Jump to symbol: 'ExtendedSetLikeConstructor'") +interface, or the +[`SetLikeConstructor`](#setlikeconstructor "Jump to symbol: 'SetLikeConstructor'") +interface, depending on whether the current environment supports composition +methods introduced by the TC39 Set Methods Proposal. + +If the current environment supports the composition methods, this type will +resolve to the +[`ExtendedSetLikeConstructor`](#extendedsetlikeconstructor "Jump to symbol: 'ExtendedSetLikeConstructor'") +interface. Otherwise, it will resolve to the +[`SetLikeConstructor`](#setlikeconstructor "Jump to symbol: 'SetLikeConstructor'") +interface. + +###### See Also + +- [`SupportedSetLike`](#supportedsetlike "Jump to symbol: 'SupportedSetLike'") + for a similar type that represents the full set-like object. + +## `TypedArray` + +#### Signature + +```ts ignore +export type TypedArray = + InstanceType>; +``` + +Represents an instance of a typed array, which is a view over a raw binary data +buffer (e.g. `ArrayBuffer`) of a fixed-size. The following are the supported +native typed array types: + +- `Uint8Array` +- `Uint8ClampedArray` +- `Uint16Array` +- `Uint32Array` +- `Int8Array` +- `Int16Array` +- `Int32Array` +- `Float16Array` (ES2024) +- `Float32Array` +- `Float64Array` +- `BigInt64Array` +- `BigUint64Array` + +##### Type Parameters + +- **`T`** extends `ArrayBufferLike` (default: `ArrayBufferLike`) + +--- + +###### Category + +`Binary Data Structures` + +###### See Also + +- [isTypedArray](#istypedarray "Jump to symbol: 'isTypedArray'") to check if a + value is this type at runtime. + +## `Uint16` + +#### Signature + +```ts ignore +export type Uint16 = Cast; +``` + +Casts a value into an unsigned 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `Uint32` + +#### Signature + +```ts ignore +export type Uint32 = Cast; +``` + +Casts a value into an unsigned 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `Uint8` + +#### Signature + +```ts ignore +export type Uint8 = Cast; +``` + +Casts a value into an unsigned 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint8, type Uint8 } from "@nick/is/uint8"; + +let i = 1 as Uint8, y = 0; + +if (isUint8(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint8'. +``` + +## `UniqueSymbol` + +#### Signature + +```ts ignore +export type UniqueSymbol = Brand; +``` + +Branded type representing a unique symbol, which is a primitive symbol that was +created using the `Symbol()` function, and is not a registered symbol created +with `Symbol.for()`, nor a well-known symbol defined on the global `Symbol` +object. + +###### Category + +`Primitives` + +## `Unwrap` + +#### Signature + +```ts ignore +export type Unwrap = U extends Cast ? [N, T] : [U, never]; +``` + +Unwraps a type that has been cast with [Cast](#cast "Jump to symbol: 'Cast'") +into a tuple of the original value and the specific type it was cast to (or +"branded" with). If the given type was _not_ cast with +[Cast](#cast "Jump to symbol: 'Cast'"), it will resolve to a tuple containing +the original value and `never`, respectively. + +##### Type Parameters + +- **`U`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { Cast, Unwrap } from "jsr:@nick/is/number"; + +type Int_3 = Cast<3, INTEGER>; + +function unwrap(value: T): Unwrap[0] { + return value as Unwrap[0]; +} +``` + +## `WellKnownSymbol` + +#### Signature + +```ts ignore +export type WellKnownSymbol = ValueOf<{ + [K in [object Object]]: SymbolConstructor[K] + }>; +``` + +Union type representing all of the well-known symbols defined on the global +`Symbol` object in the current runtime environment. + +###### Category + +`Primitives` + +## `Whitespace` + +#### Signature + +```ts ignore +export type Whitespace = typeof WHITESPACE_CHARS[number] & {}; +``` + +A union of all whitespace characters, as defined by the Unicode standard. This +includes characters such as spaces, tabs, newlines, and additional Unicode +whitespace characters that are not typically visible in text. + +This type is particularly useful for type-level programming, specifically when +developing string manipulation types that need to account for various types of +whitespace characters rather than a simple ASCII space. + +For example, if one wanted to create a type-level utility to split a string +literal into its constituent parts using whitespace and punctuation as its +delimiters, it could be done quite easily using this type. + +###### Category + +`Types` + +###### Tags + +`whitespace` + +## `WhitespaceCode` + +#### Signature + +```ts ignore +export type WhitespaceCode = typeof WHITESPACE_CODES[number]; +``` + +Union of all whitespace character codes, as defined by the Unicode standard. +This includes characters such as spaces, tabs, newlines, and additional Unicode +whitespace characters that are not typically visible. + +###### Category + +`Types` + +###### Tags + +`whitespace` `char code` + +## `WhitespaceLike` + +#### Signature + +```ts ignore +export type WhitespaceLike = WhitespaceString | Whitespace | WhitespaceCode; +``` + +A union type that can be either a string or a whitespace character code. + +This is the type used in the +[`isWhitespaceLike`](#iswhitespacelike "Jump to symbol: 'isWhitespaceLike'") +function to determine if a value is either a string or a whitespace character +code. + +###### Category + +`Types` + +###### Tags + +`whitespace` + +## `WhitespaceString` + +#### Signature + +```ts ignore +export type WhitespaceString = S & WhitespaceBrand; +``` + +Represents a string that has been verified at runtime to only consist of +whitespace characters. This is a nominal (branded) type that is distinct from a +regular string type. + +##### Type Parameters + +- **`S`** extends `string` (default: `string`) + +--- + +###### Category + +`Types` + +###### Tags + +`whitespace` `branded` + +## `Zero` + +#### Signature + +```ts ignore +export type Zero = Cast; +``` + +Casts a value into a zero type. If the value is not a number, it will resolve to +`never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isZero, type Zero } from "jsr:@type/number/zero"; + +let x = 0 as Zero, y = 1; + +if (isZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Zero'. +``` + +## `ArrayIterator` + +Represents a array iterator. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +##### Extends `IterableIterator` + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "Array Iterator"; +``` + +--- + +## `AsyncFunction` + +##### Type Parameters + +- **`TReturn`** (default: `any`) + +--- + +### Call Signatures + +```ts +(...args: any[]): Promise; +``` + +--- + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "AsyncFunction"; +``` + +--- + +## `Class` + +###### Category + +`Types` + +#### Examples + +```ts +import { isClass } from "jsr:@nick/is/class"; + +class Foo {} +console.log(isClass(Foo)); // true + +const Bar = function () { + this.foo = "bar"; + return this; +}; +console.log(isClass(Bar)); // false + +const Baz = () => {}; +console.log(isClass(Baz)); // false +``` + +##### Type Parameters + +- **`T`** (default: `any`) +- **`A`** extends `readonly unknown[]` (default: `readonly any[]`) +- **`P`** extends `object | null` (default: `Is`) + +--- + +### Properties + +#### prototype + +```ts +readonly prototype: P; +``` + +--- + +## `Closer` + +An abstract interface which when implemented provides an interface to close +files/resources that were previously opened. + +###### Category + +`I/O` + +### Methods + +#### close + +```ts +close(): void; +``` + +Closes the resource, "freeing" the backing file/resource. + +--- + +## `Constructor` + +Represents a constructor function that creates instances of type `T`. + +###### Category + +`Types` + +##### Type Parameters + +- **`T`** (default: `unknown`) +- **`A`** extends `readonly unknown[]` (default: `readonly unknown[]`) + +--- + +### Properties + +#### prototype + +```ts +readonly prototype: Prototype; +``` + +--- + +## `EnumLike` + +Represents an "enum-like" object, which is a plain object composed of either all +string keys and string values, or a two-way mapping of string keys to numeric +values (and vice versa). + +This is a supertype of the type of object created by TypeScript's builtin `enum` +keyword. Its primary consumer is the +[`isEnum`](#isenum "Jump to symbol: 'isEnum'") function. + +###### Category + +`Types` + +###### Tags + +`enum` `objects` + +#### Examples + +```ts +// when we create an enum with constant numeric values, the TypeScript +// compiler auto-generates an implicit reverse-mapping from the values +// back to their respective keys, providing us with the capability to +// access the keys by their values. +enum Priority { + Low = 0x0, + Medium = 0x1, + High = 0x2, + Insane = 0xFF, +} + +// the actual object generated by the enum syntax above looks like this: +const Priority = { + Low: 0, + Medium: 1, + High: 2, + Insane: 255, + "0": "Low", + "1": "Medium", + "2": "High", + "255": "Insane", +} satisfies EnumLike; + +// this provides us with the ability to access a key even when we only have +// its value, a language feature that is popular in other OOP languages such +// as C#, Java, and C++: + +console.log(Priority.High); // 2 +console.log(Priority[2]); // "High" +console.assert(Priority.High === Priority[Priority[2]]); +console.assert(Priority[2] === Priority[Priority.High]); +``` + +##### Type Parameters + +- **`K`** extends `string | number` (default: `string | number`) +- **`V`** extends `string | number` (default: `string | number`) + +--- + +### Index Signatures + +#### EnumLike + +```ts +readonly [key: string]: K | V | undefined +``` + +#### EnumLike + +```ts +readonly [index: number]: K +``` + +--- + +## `ExtendedSetLike` + +A `ExtendedSetLike` object is a collection of values, where each value may only +occur once. The values in a `ExtendedSetLike` can be either primitive values or +object references. The keys of a `ExtendedSetLike` are the same as the values. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +##### Extends `SetLike` + +### Methods + +#### union + +```ts +union( + other: ReadonlyCollection, + ): ExtendedSetLike; +``` + +##### Parameters + +| Name | Info | +| :---------- | :------------------------------------------------ | +| **`other`** | The other set-like object to merge with this one. | + +##### Returns + +a new [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object containing all the elements in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +and also all the elements in the [`other`](#other "Jump to symbol: 'other'"). + +#### intersection + +```ts +intersection( + other: ReadonlyCollection, + ): ExtendedSetLike; +``` + +##### Parameters + +| Name | Info | +| :---------- | :---------------------------------------------------- | +| **`other`** | The other set-like object to intersect with this one. | + +##### Returns + +a new [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object containing all the elements which are both in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +and in the [`other`](#other "Jump to symbol: 'other'"). + +#### difference + +```ts +difference( + other: ReadonlyCollection, + ): ExtendedSetLike; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a new [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object containing all the elements in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +which are not also in the [`other`](#other "Jump to symbol: 'other'"). + +#### symmetricDifference + +```ts +symmetricDifference( + other: ReadonlyCollection, + ): ExtendedSetLike; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a new ExtendedSetLike object containing all the elements which are in either +this [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object or in the [`other`](#other "Jump to symbol: 'other'"), but not in both. + +#### isSubsetOf + +```ts +isSubsetOf( + other: ReadonlyCollection, + ): boolean; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a boolean indicating whether all the elements in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +are also in the [`other`](#other "Jump to symbol: 'other'"). + +#### isSupersetOf + +```ts +isSupersetOf( + other: ReadonlyCollection, + ): boolean; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a boolean indicating whether all the elements in the +[`other`](#other "Jump to symbol: 'other'") are also in this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object. + +#### isDisjointFrom + +```ts +isDisjointFrom( + other: ReadonlyCollection, + ): boolean; +``` + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------------------------------- | +| **`other`** | The other set-like object to compare with this one. | + +##### Returns + +a boolean indicating whether this +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") object +has no elements in common with the [`other`](#other "Jump to symbol: 'other'"). + +--- + +## `ExtendedSetLikeConstructor` + +Represents a constructor function for an +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object. + +### Properties + +#### prototype + +```ts +readonly prototype: ExtendedSetLike; +``` + +--- + +## `MapIterator` + +Represents a map iterator. + +##### Type Parameters + +- **`K`** +- **`V`** + +--- + +##### Extends `IterableIterator<[K,V]>` + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "Map Iterator" | "Map Entries"; +``` + +--- + +## `MapLike` + +Map-like objects are collections of keys and values, where each key may only +appear once in the collection. + +###### Category + +`Types` + +##### Type Parameters + +- **`K`** +- **`V`** + +--- + +##### Extends `Iterable<[K,V]>` + +### Properties + +#### size + +```ts +readonly size: number; +``` + +Gets the number of elements in the collection. + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: string; +``` + +--- + +### Methods + +#### has + +```ts +has(key: K): boolean; +``` + +Tests whether a key is present in the collection. + +##### Parameters + +| Name | Info | +| :-------- | :----------------- | +| **`key`** | The key to lookup. | + +##### Returns + +`true` if the key is present in the collection; otherwise, `false`. + +#### get + +```ts +get(key: K): V | undefined; +``` + +Gets the value associated with the provided key, if it exists. + +##### Parameters + +| Name | Info | +| :-------- | :----------------- | +| **`key`** | The key to lookup. | + +##### Returns + +The value associated with the provided key, or `undefined`. + +#### set + +```ts +set(key: K, value: V): this; +``` + +Sets the value in the collection associated with the provided key. + +##### Parameters + +| Name | Info | +| :---------- | :---------------- | +| **`key`** | The key to set. | +| **`value`** | The value to set. | + +##### Returns + +The collection. + +#### clear + +```ts +clear(): void; +``` + +Removes all entries from the collection. + +#### delete + +```ts +delete(key: K): boolean; +``` + +Removes a key from the collection. + +##### Parameters + +| Name | Info | +| :-------- | :----------------- | +| **`key`** | The key to remove. | + +##### Returns + +`true` if the delete operation was successful, otherwise `false`. + +#### keys + +```ts +keys(): IterableIterator; +``` + +Returns an `IterableIterator` for the keys present in the collection. + +#### values + +```ts +values(): IterableIterator; +``` + +Returns an `IterableIterator` for the values present in the collection. + +#### entries + +```ts +entries(): IterableIterator< + [K, V] + >; +``` + +Returns an `IterableIterator` for the entries present in the collection. Each +entry is a tuple containing the key and value for each element. + +#### forEach + +```ts +forEach( + cb: (this: This, value: V, key: K, map: MapLike) => void, + thisArg?: This, + ): void; +``` + +Executes a provided function once per each key/value pair in the collection. + +##### Parameters + +| Name | Info | +| :------------ | :------------------------------------------------------ | +| **`cb`** | The callback to execute. | +| **`thisArg`** | The value to use as `this` when executing the callback. | + +##### Returns + +Nothing. + +#### [Symbol.iterator] + +```ts +[Symbol.iterator](): IterableIterator< + [K, V] + >; +``` + +Returns an `IterableIterator` for the entries present in the collection. + +--- + +## `MapLikeConstructor` + +A constructor function for creating new `MapLike` objects. + +###### Category + +`Types` + +### Properties + +#### prototype + +```ts +readonly prototype: MapLike; +``` + +--- + +## `Reader` + +An abstract interface which when implemented provides an interface to read bytes +into an array buffer asynchronously. + +###### Category + +`I/O` + +### Methods + +#### read + +```ts +read( + p: Uint8Array, + ): Promise; +``` + +Reads up to `p.byteLength` bytes into `p`. It resolves to the number of bytes +read (`0` < `n` <= `p.byteLength`) and rejects if any error encountered. Even if +`read()` resolves to `n` < `p.byteLength`, it may use all of `p` as scratch +space during the call. If some data is available but not `p.byteLength` bytes, +`read()` conventionally resolves to what is available instead of waiting for +more. + +When `read()` encounters end-of-file condition, it resolves to EOF (null). When +`read()` encounters an error, it rejects with an error. + +Callers should always process the `n` > `0` bytes returned before considering +the EOF (`null`). Doing so correctly handles I/O errors that happen after +reading some bytes and also both of the allowed EOF behaviors. + +Implementations should not retain a reference to `p`. + +--- + +## `ReaderSync` + +An abstract interface which when implemented provides an interface to read bytes +into an array buffer synchronously. + +###### Category + +`I/O` + +### Methods + +#### readSync + +```ts +readSync( + p: Uint8Array, + ): number | null; +``` + +Reads up to `p.byteLength` bytes into `p`. It resolves to the number of bytes +read (`0` < `n` <= `p.byteLength`) and rejects if any error encountered. Even if +`readSync()` returns `n` < `p.byteLength`, it may use all of `p` as scratch +space during the call. If some data is available but not `p.byteLength` bytes, +`readSync()` conventionally returns what is available instead of waiting for +more. + +When `readSync()` encounters end-of-file condition, it returns EOF (`null`). + +When `readSync()` encounters an error, it throws with an error. + +Callers should always process the `n` > `0` bytes returned before considering +the EOF (`null`). Doing so correctly handles I/O errors that happen after +reading some bytes and also both of the allowed EOF behaviors. + +Implementations should not retain a reference to `p`. + +--- + +## `ReadonlyCollection` + +Set-like objects are collections of unique values (each value may only occur +once). The `ReadonlyCollection` interface defines the bare minimum requirements +for an object to be considered "set-like" in JavaScript; that is, it must have: + +- a `has` method, which tests whether a given value is present in the set, + returning a boolean value indicating the result. +- a `keys` method, which returns an `IterableIterator` for the keys present in + the set. Since set collections are keyed by their values, the `keys` method + actually iterates over the **_values_** in the set. +- a read-only `size` property (getter), which returns the number of values in + the set at any given time. + +This interface the base for the `SetLike` interface (hence its name), which +extends it with additional methods like `add`, `delete`, `clear`, `forEach`, +`values`, and `entries` to provide a more complete API for working with Set- +like collections in JavaScript. Prior to the TC39 Proposal for Set Methods, the +`SetLike` interface was the shape of the native `Set` API in JavaScript. + +Following the introduction of the TC39 Proposal for Set Methods, the methods for +set composition (`union`, `intersection`, `difference`, etc.) were added to the +`Set` API, which necessitated the creation of the `ExtendedSetLike` interface to +represent the full API for set-like collections in JavaScript. + +Those methods require their arguments to implement the +[`ReadonlyCollection`](#readonlycollection "Jump to symbol: 'ReadonlyCollection'") +interface, rather than the full +[`SetLike`](#setlike "Jump to symbol: 'SetLike'") or +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'"). This +means you can call `Set.prototype.union` with a `Set`, `Map`, or even an +`IterableWeakSet` object, since they all implement the `ReadonlyCollection` API. + +###### See Also + +- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_objects + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +### Properties + +#### size + +```ts +readonly size: number; +``` + +##### Returns + +The number of elements in the collection. + +--- + +### Methods + +#### has + +```ts +has(value: T): boolean; +``` + +Tests whether a given value is present in the collection. + +##### Parameters + +| Name | Info | +| :---------- | :------------------- | +| **`value`** | The value to lookup. | + +##### Returns + +`true` if the value is in the collection; otherwise, `false`. + +#### keys + +```ts +keys(): IterableIterator; +``` + +Gets an `IterableIterator` for the keys present in the collection. + +##### Returns + +An iterator of the keys in the collection. + +--- + +## `ReadonlyCollectionConstructor` + +Represents a constructor function for a +[`ReadonlyCollection`](#readonlycollection "Jump to symbol: 'ReadonlyCollection'") +object, which is the base implementation of a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object, without any of the additional composition methods like `union` or +`intersection`. + +###### See Also + +- [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") for + the full interface with composition methods. +- [`SetLike`](#setlike "Jump to symbol: 'SetLike'") for the core interface + without composition methods. + +### Properties + +#### prototype + +```ts +readonly prototype: ReadonlyCollection; +``` + +--- + +## `SetIterator` + +Represents a set iterator. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +##### Extends `IterableIterator` + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "Set Iterator" | "Set Entries"; +``` + +--- + +## `SetLike` + +Represents the core functionality of a `SetLike` object, which is the base +implementation of a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object, without any additional composition methods (`union`, `intersection`, +`difference`, etc). This was the native `Set` API prior to the TC39 Set Methods +Proposal's introduction. + +###### See Also + +- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set +- [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") for + the full interface with composition methods. +- [`SetLikeConstructor`](#setlikeconstructor "Jump to symbol: 'SetLikeConstructor'") + for the constructor interface. + +##### Type Parameters + +- **`T`** (default: `unknown`) + +--- + +##### Extends `Iterable`, `ReadonlyCollection` + +### Properties + +#### size + +```ts +readonly size: number; +``` + +##### Returns + +The number of elements in the collection. + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: string; +``` + +--- + +### Methods + +#### add + +```ts +add(value: T): this; +``` + +Adds the given value to the collection, if it does not already exist. + +##### Parameters + +| Name | Info | +| :---------- | :---------------- | +| **`value`** | The value to add. | + +##### Returns + +The collection. + +#### has + +```ts +has(value: T): boolean; +``` + +Tests whether a key is present in the collection. + +##### Parameters + +| Name | Info | +| :---------- | :----------------- | +| **`value`** | The key to lookup. | + +##### Returns + +`true` if the value is in the collection; otherwise, `false`. + +#### clear + +```ts +clear(): void; +``` + +Removes all values from the collection. + +#### delete + +```ts +delete(value: T): boolean; +``` + +Removes a value from the collection. + +##### Parameters + +| Name | Info | +| :---------- | :------------------- | +| **`value`** | The vakue to remove. | + +##### Returns + +`true` if the operation was successful; otherwise, `false`. + +#### forEach + +```ts +forEach( + cb: (this: This, value: T, value2: T, set: this) => void, + thisArg?: This, + ): void; +``` + +Executes a provided function once per each entry in the collection. The callback +is invoked with the current value for both the first and second arguments (to +maintain a similar signature as `forEach` on other iterable objects like `Map` +and `Array`). + +##### Parameters + +| Name | Info | +| :------------ | :------------------------------------------------------ | +| **`cb`** | The callback to execute. | +| **`thisArg`** | The value to use as `this` when executing the callback. | + +##### Returns + +Nothing. + +#### keys + +```ts +keys(): IterableIterator; +``` + +##### Returns + +an Iterable of the values in the collection. + +#### values + +```ts +values(): IterableIterator; +``` + +##### Returns + +an `IterableIterator` for the values present in the collection. + +#### entries + +```ts +entries(): IterableIterator< + [T, T] + >; +``` + +##### Returns + +an `IterableIterator` of the entries present in the collection. Each entry is a +tuple containing the key and value for each element. + +#### [Symbol.iterator] + +```ts +[Symbol.iterator](): IterableIterator< + T + >; +``` + +Returns an iterator of the [`values`](#values "Jump to symbol: 'values'") in the +set. + +--- + +## `SetLikeConstructor` + +Represents a constructor function for a +[`SetLike`](#setlike "Jump to symbol: 'SetLike'") object, which is the base +implementation of a +[`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") +object, without any of the additional composition methods like `union` or +`intersection`. + +###### See Also + +- [`ExtendedSetLike`](#extendedsetlike "Jump to symbol: 'ExtendedSetLike'") for + the full interface with composition methods. +- [`SetLike`](#setlike "Jump to symbol: 'SetLike'") for the core interface + without composition methods. + +### Properties + +#### prototype + +```ts +readonly prototype: SetLike; +``` + +--- + +## `StringIterator` + +Represents a string iterator. + +##### Type Parameters + +- **`T`** extends `string` (default: `string`) + +--- + +##### Extends `IterableIterator[number]>` + +### Properties + +#### [Symbol.toStringTag] + +```ts +readonly [Symbol.toStringTag]: "String Iterator"; +``` + +--- + +## `TemplateObject` + +A template strings object is an object with a `raw` property containing an array +of strings. This type is used to loosely represent the first argument passed to +a tagged template function, which is a template strings array. + +Note: while all `TemplateStringsArray` values are `TemplateObject`s, not all +`TemplateObject`s are `TemplateStringsArray`s. + +###### Category + +`Template Literals` + +### Properties + +#### raw + +```ts +readonly raw: readonly string[]; +``` + +--- + +## `TemplateStringsArray` + +A template strings array is an array of strings with an own property named `raw` +that is also an array of strings. This is the type of array provided to tagged +template literals for the first argument, and is represented as the type +`TemplateStringsArray` in TypeScript. + +Note: while all `TemplateStringsArray` values are `TemplateStringsObject`s, not +all `TemplateStringsObject`s are `TemplateStringsArray`s. + +###### Category + +`Types` + +###### Tags + +`TemplateStringsArray` + +##### Extends `ReadonlyArray` + +### Properties + +#### raw + +```ts +readonly raw: ReadonlyArray; +``` + +--- + +## `Writer` + +An abstract interface which when implemented provides an interface to write +bytes from an array buffer to a file/resource asynchronously. + +###### Category + +`I/O` + +### Methods + +#### write + +```ts +write( + p: Uint8Array, + ): Promise; +``` + +Writes `p.byteLength` bytes from `p` to the underlying data stream. It resolves +to the number of bytes written from `p` (`0` <= `n` <= `p.byteLength`) or reject +with the error encountered that caused the write to stop early. `write()` must +reject with a non-null error if would resolve to `n` < `p.byteLength`. `write()` +must not modify the slice data, even temporarily. + +This function is one of the lowest level APIs and most users should not work +with this directly, but rather use +[`writeAll()`](https://deno.land/std/streams/write_all.ts?s=writeAll) from +`std/streams/write_all.ts` instead. + +Implementations should not retain a reference to `p`. + +--- + +## `WriterSync` + +An abstract interface which when implemented provides an interface to write +bytes from an array buffer to a file/resource synchronously. + +###### Category + +`I/O` + +### Methods + +#### writeSync + +```ts +writeSync( + p: Uint8Array, + ): number; +``` + +Writes `p.byteLength` bytes from `p` to the underlying data stream. It returns +the number of bytes written from `p` (`0` <= `n` <= `p.byteLength`) and any +error encountered that caused the write to stop early. `writeSync()` must throw +a non-null error if it returns `n` < `p.byteLength`. `writeSync()` must not +modify the slice data, even temporarily. + +Implementations should not retain a reference to `p`. + +--- diff --git a/docs/uint16-array.md b/docs/uint16-array.md new file mode 100644 index 0000000..f12bce2 --- /dev/null +++ b/docs/uint16-array.md @@ -0,0 +1,35 @@ +# @nick/is/uint16-array + +## `isUint16Array` + +#### Signature + +```ts ignore +function isUint16Array(it: unknown): it is Uint16Array; +``` + +Check if the given value is a `Uint16Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Uint16Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isUint16Array } from "jsr:@nick/is/uint16array"; + +const arr = new Uint16Array(8); +isUint16Array(arr); // true +isUint16Array(arr.buffer); // false +``` diff --git a/docs/uint32-array.md b/docs/uint32-array.md new file mode 100644 index 0000000..3a2b83e --- /dev/null +++ b/docs/uint32-array.md @@ -0,0 +1,35 @@ +# @nick/is/uint32-array + +## `isUint32Array` + +#### Signature + +```ts ignore +function isUint32Array(it: unknown): it is Uint32Array; +``` + +Check if the given value is a `Uint32Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Uint32Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isUint32Array } from "jsr:@nick/is/uint32array"; + +const arr = new Uint32Array(8); +isUint32Array(arr); // true +isUint32Array(arr.buffer); // false +``` diff --git a/docs/uint8-array.md b/docs/uint8-array.md new file mode 100644 index 0000000..296649d --- /dev/null +++ b/docs/uint8-array.md @@ -0,0 +1,35 @@ +# @nick/is/uint8-array + +## `isUint8Array` + +#### Signature + +```ts ignore +function isUint8Array(it: unknown): it is Uint8Array; +``` + +Check if the given value is a `Uint8Array` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Uint8Array` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isUint8Array } from "jsr:@nick/is/uint8array"; + +const arr = new Uint8Array(8); +isUint8Array(arr); // true +isUint8Array(arr.buffer); // false +``` diff --git a/docs/uint8-clamped-array.md b/docs/uint8-clamped-array.md new file mode 100644 index 0000000..85c71de --- /dev/null +++ b/docs/uint8-clamped-array.md @@ -0,0 +1,35 @@ +# @nick/is/uint8-clamped-array + +## `isUint8ClampedArray` + +#### Signature + +```ts ignore +function isUint8ClampedArray(it: unknown): it is Uint8ClampedArray; +``` + +Check if the given value is a `Uint8ClampedArray` instance. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `Uint8ClampedArray` instance, `false` otherwise. + +###### Category + +`Binary Data Structures` + +#### Examples + +```ts +import { isUint8ClampedArray } from "jsr:@nick/is/uint8clampedarray"; + +const arr = new Uint8ClampedArray(8); +isUint8ClampedArray(arr); // true +isUint8ClampedArray(arr.buffer); // false +``` diff --git a/docs/undefined.md b/docs/undefined.md new file mode 100644 index 0000000..3ffe87a --- /dev/null +++ b/docs/undefined.md @@ -0,0 +1,52 @@ +# @nick/is/undefined + +## `isUndefined` + +#### Signature + +```ts ignore +function isUndefined(it: unknown): it is undefined; +``` + +Checks if the value is `undefined`, and nothing else. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `undefined`, or `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isUndefined } from "jsr:@nick/is/undefined"; + +isUndefined(null); // false +isUndefined(undefined); // true +isUndefined(0); // false +isUndefined(void 0); // true +isUndefined(""); // false +``` + +```ts +import { isUndefined } from "jsr:@nick/is/undefined"; + +let value: number | undefined; +if (isUndefined(value)) { + value; + // ^? let value: undefined + value = 0; + // ^? let value: number | undefined +} else { + value += 1; + // ^? let value: number +} +``` diff --git a/docs/unique-symbol.md b/docs/unique-symbol.md new file mode 100644 index 0000000..9e23760 --- /dev/null +++ b/docs/unique-symbol.md @@ -0,0 +1,50 @@ +# @nick/is/unique-symbol + +## `isUniqueSymbol` + +#### Signature + +```ts ignore +function isUniqueSymbol(it: unknown): it is UniqueSymbol; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a unique symbol, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isUniqueSymbol } from "jsr:@nick/is/unique-symbol"; + +isUniqueSymbol(Symbol("foo")); // true +isUniqueSymbol(Symbol.iterator); // false +isUniqueSymbol(Symbol.for("foo")); // false +``` + +## `UniqueSymbol` + +#### Signature + +```ts ignore +export type UniqueSymbol = Brand; +``` + +Branded type representing a unique symbol, which is a primitive symbol that was +created using the `Symbol()` function, and is not a registered symbol created +with `Symbol.for()`, nor a well-known symbol defined on the global `Symbol` +object. + +###### Category + +`Primitives` diff --git a/docs/url-search-params.md b/docs/url-search-params.md new file mode 100644 index 0000000..9d0a4d2 --- /dev/null +++ b/docs/url-search-params.md @@ -0,0 +1,41 @@ +# @nick/is/url-search-params + +## `isURLSearchParams` + +#### Signature + +```ts ignore +function isURLSearchParams(it: unknown): it is URLSearchParams; +``` + +Checks if a value is a URLSearchParams object. + +This function is useful for checking if a value is an instance of the native +`URLSearchParams` class, without leaning on the `instanceof` operator (which +known to be unreliable in certain environments and across different realms). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a URLSearchParams object, `false` otherwise. + +###### Category + +`Web APIs` + +#### Examples + +```ts +import { isURLSearchParams } from "jsr:@nick/is/url-search-params"; + +console.log(isURLSearchParams(new URLSearchParams())); // true +console.log(isURLSearchParams(new URLSearchParams("a=1&b=2"))); // true +console.log(isURLSearchParams(new URL("https://foobar.com?a=1").searchParams)); // true +console.log(isURLSearchParams({})); // false +console.log(isURLSearchParams(new URL("data:"))); // false +``` diff --git a/docs/url-string.md b/docs/url-string.md new file mode 100644 index 0000000..f2438a8 --- /dev/null +++ b/docs/url-string.md @@ -0,0 +1,56 @@ +# @nick/is/url-string + +## `isURLString` + +#### Signature + +```ts ignore +function isURLString(it: unknown): it is URLString; +``` + +Checks if a value is a string that is a valid, parsable URL capable of being +passed to the `URL` constructor. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a URL string, `false` otherwise. + +###### Category + +`Web APIs` + +#### Examples + +```ts +import { isURLString } from "jsr:@nick/is/url-string"; + +console.log(isURLString("https://example.com")); // true +console.log(isURLString("data:")); // true +console.log(isURLString("https://foo")); // false +console.log(isURLString("example.com")); // false +``` + +## `URLString` + +#### Signature + +```ts ignore +export type URLString = Brand; +``` + +A string that is a valid, parsable URL capable of being passed to the `URL` +constructor. This is a branded string type, meaning it behaves as a nominal type +that is distinct from other string values. The only way to narrow a string to a +[`URLString`](#urlstring "Jump to symbol: 'URLString'") type is by validating it +first with the [`isURLString`](#isurlstring "Jump to symbol: 'isURLString'") +type guard function. + +###### Categories + +`Web APIs` `Types` diff --git a/docs/url.md b/docs/url.md new file mode 100644 index 0000000..ce1791e --- /dev/null +++ b/docs/url.md @@ -0,0 +1,34 @@ +# @nick/is/url + +## `isURL` + +#### Signature + +```ts ignore +function isURL(it: unknown): it is URL; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a URL object, `false` otherwise. + +###### Category + +`Web APIs` + +#### Examples + +```ts +import { isURL } from "jsr:@nick/is/url"; + +console.log(isURL(new URL("https://example.com"))); // true +console.log(isURL(new URL("https://example.com").toString())); // false +console.log(isURL({ href: "https://example.com" })); // false +console.log(isURL({ ...new URL("https://example.com") })); // false +``` diff --git a/docs/weak-key.md b/docs/weak-key.md new file mode 100644 index 0000000..dc4a7f0 --- /dev/null +++ b/docs/weak-key.md @@ -0,0 +1,108 @@ +# @nick/is/weak-key + +## `isWeakKey` + +#### Signature + +```ts ignore +function isWeakKey(it: unknown): it is WeakKey; +``` + +Checks if a value is valid as a weak key, meaning it can be used as a key in a +`WeakMap`, a value in a `WeakSet`, or as the target of a `WeakRef`. Weak keys +can also be used as the "unregister token" argument in both the `register` and +`unregister` methods of the `FinalizationRegistry` API. + +This always includes non-null objects, arrays, and functions. Since ES2023+ it +also includes symbols that are not globally registered via `Symbol.for`. + +##### Parameters + +| Name | Info | +| :------- | :------------------- | +| **`it`** | The value you check. | + +##### Returns + +`true` if it is a valid WeakKey, otherwise `false`. + +###### Category + +`Weak Collections` + +###### See Also + +- https://mdn.io/WeakMap for more information on `WeakMap` and weak keys. + +#### Examples + +```ts +import { isWeakKey } from "jsr:@nick/is/weak-key"; + +// objects and functions are always valid weak keys: +console.log(isWeakKey({})); // true +console.log(isWeakKey(() => {})); // true + +// starting in ES2023+, symbols are also valid weak keys: +console.log(isWeakKey(Symbol("a"))); // true +console.log(isWeakKey(Symbol.iterator)); // true + +// however, globally registered symbols are not: +console.log(isWeakKey(Symbol.for("a"))); // false + +// primitives are never valid weak keys: +console.log(isWeakKey(1)); // false +console.log(isWeakKey("a")); // false +``` + +## `WeakKey` + +#### Signature + +```ts ignore +export type WeakKey = WeakKeyTypes[keyof WeakKeyTypes]; +``` + +A value that can be used as a key in a `WeakMap`, a value in a `WeakSet`, or as +the target of a `WeakRef`. Weak keys can also be used as the "unregister token" +argument in both the `register` and `unregister` methods of the +`FinalizationRegistry` API. + +This always includes non-null objects, arrays, and functions. Since ES2023+ it +also includes symbols that are not globally registered via `Symbol.for`. + +###### Category + +`Weak Collections` + +###### Tags + +`WeakKey` + +###### See Also + +- https://mdn.io/WeakMap for more information on `WeakMap` and weak keys. + +## `WeakKeyTypes` + +The types that can be used as a weak key. + +###### Category + +`Weak Collections` + +### Properties + +#### object + +```ts +object: object; +``` + +#### symbol + +```ts +symbol: symbol; +``` + +--- diff --git a/docs/weak-map.md b/docs/weak-map.md new file mode 100644 index 0000000..21a57d9 --- /dev/null +++ b/docs/weak-map.md @@ -0,0 +1,89 @@ +# @nick/is/weak-map + +## `isWeakMap` + +#### Signature + +```ts ignore +function isWeakMap( + it: WeakMap | null | undefined, +): it is WeakMap; +``` + +Checks if [`it`](#it "Jump to symbol: 'it'") is a `WeakMap` object. For more +information on this language feature, refer to the +[MDN Documentation](https://mdn.io/WeakMap). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +true if it is a `WeakMap`, otherwise false. + +###### Category + +`Weak Collections` + +###### Tags + +`WeakMap` + +#### Examples + +```ts +import { isWeakMap } from "jsr:@nick/is/weak-map"; + +const strong = new Map([[{ a: 1 }, 1], [{ b: 2 }, 2]]); +const weak1 = new WeakMap([[{ a: 1 }, 1], [{ b: 2 }, 2]]); +const weak2 = new WeakSet([{ a: 1 }, { b: 2 }]); + +isWeakMap(strong); // false +isWeakMap(weak1); // true +isWeakMap(weak2); // false +``` + +## `isWeakMap` + +#### Signature + +```ts ignore +function isWeakMap( + it: unknown, +): it is WeakMap; +``` + +Checks if [`obj`](#obj "Jump to symbol: 'obj'") is a `WeakMap` object. For more +information on this language feature, see the +[MDN Reference](https://mdn.io/WeakMap). + +##### Parameters + +| Name | Info | +| :-------- | :------------------ | +| **`obj`** | The value to check. | + +##### Returns + +true if it is a `WeakMap`, otherwise false. + +###### Category + +`Weak Collections` + +###### Tags + +`WeakMap` + +## `isWeakMap` + +#### Signature + +```ts ignore +function isWeakMap( + obj: unknown, +): obj is WeakMap; +``` diff --git a/docs/weak-ref.md b/docs/weak-ref.md new file mode 100644 index 0000000..652d6f2 --- /dev/null +++ b/docs/weak-ref.md @@ -0,0 +1,73 @@ +# @nick/is/weak-ref + +## `isWeakRef` + +#### Signature + +```ts ignore +function isWeakRef( + obj: WeakRef | null | undefined, +): obj is WeakRef; +``` + +Checks if [`obj`](#obj "Jump to symbol: 'obj'") is a WeakRef. For more +information on this type of object, refer to the +[MDN Documentation](https://mdn.io/WeakRef). + +##### Parameters + +| Name | Info | +| :-------- | :------------------ | +| **`obj`** | The value to check. | + +##### Returns + +true if it is a `WeakRef`, otherwise false. + +###### Category + +`Weak Collections` + +#### Examples + +```ts +import { isWeakRef } from "jsr:@nick/is/weak-ref"; + +const strong = { a: 1 }; +const weak1 = new WeakRef(strong); +const weak2 = new WeakMap([[{ a: 1 }, 1], [{ b: 2 }, 2]]); + +console.log(isWeakRef(strong)); // false +console.log(isWeakRef(weak1)); // true +console.log(isWeakRef(weak2)); // false +``` + +## `isWeakRef` + +#### Signature + +```ts ignore +function isWeakRef(obj: unknown): obj is WeakRef; +``` + +Checks if [`obj`](#obj "Jump to symbol: 'obj'") is a WeakRef. For more +information on this type of object, refer to the +[MDN Documentation](https://mdn.io/WeakRef). + +##### Parameters + +| Name | Info | +| :-------- | :------------------ | +| **`obj`** | The value to check. | + +##### Returns + +true if it is a `WeakRef`, otherwise false. + +## `isWeakRef` + +#### Signature + +```ts ignore +function isWeakRef(obj: unknown): obj is WeakRef; +``` diff --git a/docs/weak-set.md b/docs/weak-set.md new file mode 100644 index 0000000..c88b380 --- /dev/null +++ b/docs/weak-set.md @@ -0,0 +1,85 @@ +# @nick/is/weak-set + +## `isWeakSet` + +#### Signature + +```ts ignore +function isWeakSet( + it: WeakSet | null | undefined, +): it is WeakSet; +``` + +Checks if [`it`](#it "Jump to symbol: 'it'") is a `WeakSet` object. For more +information on this language feature, refer to the +[MDN Documentation](https://mdn.io/WeakSet). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +true if it is a `WeakSet`, otherwise false. + +###### Category + +`Weak Collections` + +###### Tags + +`WeakSet` + +#### Examples + +```ts +import { isWeakSet } from "jsr:@nick/is/weak-set"; + +const strong = new Set([1, 2]); +const weak1 = new WeakSet([{ a: 1 }, { b: 2 }]); +const weak2 = new WeakMap([[{ a: 1 }, 1], [{ b: 2 }, 2]]); + +console.log(isWeakSet(strong)); // false +console.log(isWeakSet(weak1)); // true +console.log(isWeakSet(weak2)); // false +``` + +## `isWeakSet` + +#### Signature + +```ts ignore +function isWeakSet(it: unknown): it is WeakSet; +``` + +Checks if [`obj`](#obj "Jump to symbol: 'obj'") is a `WeakSet` object. For more +information on this language feature, see the +[MDN Reference](https://mdn.io/WeakSet). + +##### Parameters + +| Name | Info | +| :-------- | :------------------ | +| **`obj`** | The value to check. | + +##### Returns + +true if it is a `WeakSet`, otherwise false. + +###### Category + +`Weak Collections` + +###### Tags + +`WeakSet` + +## `isWeakSet` + +#### Signature + +```ts ignore +function isWeakSet(obj: unknown): obj is WeakSet; +``` diff --git a/docs/well-known-symbol.md b/docs/well-known-symbol.md new file mode 100644 index 0000000..30ac6f1 --- /dev/null +++ b/docs/well-known-symbol.md @@ -0,0 +1,53 @@ +# @nick/is/well-known-symbol + +## `isWellKnownSymbol` + +#### Signature + +```ts ignore +function isWellKnownSymbol(it: unknown): it is WellKnownSymbol; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a well-known symbol, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isWellKnownSymbol } from "jsr:@nick/is/well-known-symbol"; + +isWellKnownSymbol(Symbol.iterator); // true +isWellKnownSymbol(Symbol.asyncIterator); // true +isWellKnownSymbol(Symbol.hasInstance); // true + +isWellKnownSymbol(Symbol.for("Symbol.iterator")); // false +isWellKnownSymbol(Symbol("Symbol.iterator")); // false +``` + +## `WellKnownSymbol` + +#### Signature + +```ts ignore +export type WellKnownSymbol = ValueOf<{ + [K in [object Object]]: SymbolConstructor[K] + }>; +``` + +Union type representing all of the well-known symbols defined on the global +`Symbol` object in the current runtime environment. + +###### Category + +`Primitives` diff --git a/docs/whitespace.md b/docs/whitespace.md new file mode 100644 index 0000000..59cb0e2 --- /dev/null +++ b/docs/whitespace.md @@ -0,0 +1,435 @@ +# @nick/is/whitespace + +## `isWhitespace` + +#### Signature + +```ts ignore +function isWhitespace( + it: S, +): it is IsWhitespace : never>; +``` + +Checks if the provided value is either a string or an iterable of strings that +consists entirely of whitespace characters. + +This function is useful for validating input data, ensuring that it contains +characters other than whitespace. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string or an iterable of strings that consists entirely +of whitespace characters, `false` otherwise. + +###### Category + +`Strings` + +###### Tags + +`whitespace` + +#### Examples + +```ts +import { isWhitespace } from "jsr:@nick/is/whitespace"; + +console.log(isWhitespace(" ")); // true +console.log(isWhitespace("abc")); // false +console.log(isWhitespace(" a ")); // false +console.log(isWhitespace("")); // false +console.log(isWhitespace(" \n\t ")); // true +``` + +## `isWhitespace` + +#### Signature + +```ts ignore +function isWhitespace(it: unknown): it is WhitespaceString; +``` + +## `isWhitespace` + +#### Signature + +```ts ignore +function isWhitespace(it: unknown): it is WhitespaceString; +``` + +## `isWhitespaceChar` + +#### Signature + +```ts ignore +function isWhitespaceChar(it: unknown): it is Whitespace; +``` + +Checks if a given character is a whitespace character. + +This function checks if the provided character is one of the recognized +whitespace characters, including spaces, tabs, newlines, and additional Unicode +whitespace characters. + +##### Parameters + +| Name | Info | +| :------- | :---------------------- | +| **`it`** | The character to check. | + +##### Returns + +`true` if the character is a whitespace character, `false` otherwise. + +###### Category + +`Strings` + +###### Tags + +`whitespace` + +#### Examples + +```ts +import { isWhitespaceChar } from "jsr:@nick/is/whitespace"; + +console.log(isWhitespaceChar(" ")); // true +console.log(isWhitespaceChar("\n")); // true +console.log(isWhitespaceChar("\t")); // true +console.log(isWhitespaceChar("a")); // false +``` + +## `isWhitespaceCode` + +#### Signature + +```ts ignore +function isWhitespaceCode(it: unknown): it is WhitespaceCode; +``` + +Checks if a given value is a whitespace character code. + +This function checks if the provided value is a number and if it is included in +the list of recognized whitespace character codes, which is exposed as the +[`WHITESPACE\_CODES`](#whitespace-codes "Jump to symbol: 'WHITESPACE_CODES'") +array. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a whitespace character code, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike( + it: S, +): it is IsWhitespace; +``` + +Checks if the provided value is either a string or an iterable of strings that +consists entirely of whitespace characters. + +This function is useful for validating input data, ensuring that it contains +characters other than whitespace. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string or an iterable of strings that consists entirely +of whitespace characters, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike( + it: N, +): it is IsWhitespaceCode; +``` + +Checks if the provided value is a whitespace character code. + +This function checks if the provided value is a number and if it is included in +the list of recognized whitespace character codes, which is exposed as the +[`WHITESPACE\_CODES`](#whitespace-codes "Jump to symbol: 'WHITESPACE_CODES'") +array. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a whitespace character code, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike(it: Iterable): it is Iterable; +``` + +Checks if the provided value is either a string or an iterable of strings that +consists entirely of whitespace characters. + +This function is useful for validating input data, ensuring that it contains +characters other than whitespace. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a string or an iterable of strings that consists entirely +of whitespace characters, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike(it: number): it is WhitespaceCode; +``` + +Checks if the provided value is a whitespace character code. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a whitespace character code, `false` otherwise. + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike(it: unknown): it is WhitespaceLike; +``` + +## `isWhitespaceLike` + +#### Signature + +```ts ignore +function isWhitespaceLike( + it: unknown, +): it is string | WhitespaceCode | Iterable; +``` + +## `IsWhitespace` + +#### Signature + +```ts ignore +export type IsWhitespace = + IsNever extends true ? False + : IsAny extends true ? True : T extends Whitespace ? True + : T extends `${Whitespace}${infer R}` ? IsWhitespace + : False; +``` + +If the given string [`T`](#t "Jump to symbol: 'T'") is whitespace, this type +will resolve to the [`True`](#true "Jump to symbol: 'True'") type parameter +(default: `true`). Otherwise, it will resolve to the +[`False`](#false "Jump to symbol: 'False'") type parameter (default: `false`). + +##### Type Parameters + +- **`T`** extends `string` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +###### Tags + +`whitespace` + +## `IsWhitespaceChar` + +#### Signature + +```ts ignore +export type IsWhitespaceChar = + T extends Whitespace ? True : False; +``` + +Type-level predicate that checks if a given string +[`T`](#t "Jump to symbol: 'T'") is a whitespace character. If +[`T`](#t "Jump to symbol: 'T'") is a whitespace character, it will resolve to +the [`True`](#true "Jump to symbol: 'True'") type parameter (default: `true`). +Otherwise, it will resolve to the [`False`](#false "Jump to symbol: 'False'") +type parameter (default: `false`). + +The compile-time equivalent of the +[`isWhitespaceChar`](#iswhitespacechar "Jump to symbol: 'isWhitespaceChar'") +function. + +##### Type Parameters + +- **`T`** extends `string` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +## `IsWhitespaceCode` + +#### Signature + +```ts ignore +export type IsWhitespaceCode = + T extends WhitespaceCode ? True : False; +``` + +Type-level predicate that checks if a given string +[`T`](#t "Jump to symbol: 'T'") is a whitespace character code. If +[`T`](#t "Jump to symbol: 'T'") is a whitespace character code, it will resolve +to the [`True`](#true "Jump to symbol: 'True'") type parameter (default: +`true`). Otherwise, it will resolve to the +[`False`](#false "Jump to symbol: 'False'") type parameter (default: `false`). + +The compile-time equivalent of the +[`isWhitespaceCode`](#iswhitespacecode "Jump to symbol: 'isWhitespaceCode'") +function. + +##### Type Parameters + +- **`T`** extends `number` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +## `Whitespace` + +#### Signature + +```ts ignore +export type Whitespace = typeof WHITESPACE_CHARS[number] & {}; +``` + +A union of all whitespace characters, as defined by the Unicode standard. This +includes characters such as spaces, tabs, newlines, and additional Unicode +whitespace characters that are not typically visible in text. + +This type is particularly useful for type-level programming, specifically when +developing string manipulation types that need to account for various types of +whitespace characters rather than a simple ASCII space. + +For example, if one wanted to create a type-level utility to split a string +literal into its constituent parts using whitespace and punctuation as its +delimiters, it could be done quite easily using this type. + +###### Category + +`Types` + +###### Tags + +`whitespace` + +## `WhitespaceCode` + +#### Signature + +```ts ignore +export type WhitespaceCode = typeof WHITESPACE_CODES[number]; +``` + +Union of all whitespace character codes, as defined by the Unicode standard. +This includes characters such as spaces, tabs, newlines, and additional Unicode +whitespace characters that are not typically visible. + +###### Category + +`Types` + +###### Tags + +`whitespace` `char code` + +## `WhitespaceLike` + +#### Signature + +```ts ignore +export type WhitespaceLike = WhitespaceString | Whitespace | WhitespaceCode; +``` + +A union type that can be either a string or a whitespace character code. + +This is the type used in the +[`isWhitespaceLike`](#iswhitespacelike "Jump to symbol: 'isWhitespaceLike'") +function to determine if a value is either a string or a whitespace character +code. + +###### Category + +`Types` + +###### Tags + +`whitespace` + +## `WhitespaceString` + +#### Signature + +```ts ignore +export type WhitespaceString = S & WhitespaceBrand; +``` + +Represents a string that has been verified at runtime to only consist of +whitespace characters. This is a nominal (branded) type that is distinct from a +regular string type. + +##### Type Parameters + +- **`S`** extends `string` (default: `string`) + +--- + +###### Category + +`Types` + +###### Tags + +`whitespace` `branded` diff --git a/docs/writable-stream.md b/docs/writable-stream.md new file mode 100644 index 0000000..939e888 --- /dev/null +++ b/docs/writable-stream.md @@ -0,0 +1,40 @@ +# @nick/is/writable-stream + +## `isWritableStream` + +#### Signature + +```ts ignore +function isWritableStream(it: unknown): it is WritableStream; +``` + +Checks if [it](#it "Jump to symbol: 'it'") is a `WritableStream` object. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a `WritableStream`, `false` otherwise. + +###### Category + +`Streams` + +#### Examples + +```ts +import { isWritableStream } from "jsr:@nick/is/writable-stream"; +a; +const stream = new WritableStream(); +isWritableStream(stream); // true + +const stream2 = new TransformStream(); +isWritableStream(stream2); // false + +const stream3 = new ReadableStream(); +isWritableStream(stream3); // false +``` diff --git a/docs/writer-sync.md b/docs/writer-sync.md new file mode 100644 index 0000000..57b5f3d --- /dev/null +++ b/docs/writer-sync.md @@ -0,0 +1,65 @@ +# @nick/is/writer-sync + +## `isWriterSync` + +#### Signature + +```ts ignore +function isWriterSync(it: unknown): it is WriterSync; +``` + +Checks if a given value is a synchronous writer, which is an object that +implements a `writeSync` method as per Deno's `WriterSync` interface. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a synchronous writer, `false` otherwise. + +###### Category + +`I/O` + +#### Examples + +```ts +import { isWriterSync } from "jsr:@nick/is/writer-sync"; + +const file = Deno.openSync("file.txt", { write: true }); +isWriterSync(file); // true + +const socket = new WebSocket("ws://example.com"); +isWriterSync(socket); // false +``` + +## `WriterSync` + +An abstract interface which when implemented provides an interface to write +bytes from an array buffer to a file/resource synchronously. + +###### Category + +`I/O` + +### Methods + +#### writeSync + +```ts +writeSync(p: Uint8Array): number; +``` + +Writes `p.byteLength` bytes from `p` to the underlying data stream. It returns +the number of bytes written from `p` (`0` <= `n` <= `p.byteLength`) and any +error encountered that caused the write to stop early. `writeSync()` must throw +a non-null error if it returns `n` < `p.byteLength`. `writeSync()` must not +modify the slice data, even temporarily. + +Implementations should not retain a reference to `p`. + +--- diff --git a/docs/writer.md b/docs/writer.md new file mode 100644 index 0000000..2cfdda8 --- /dev/null +++ b/docs/writer.md @@ -0,0 +1,70 @@ +# @nick/is/writer + +## `isWriter` + +#### Signature + +```ts ignore +function isWriter(it: unknown): it is Writer; +``` + +Checks if a given value is an asynchronous Writer, which is an object that +implements a `write` method as per Deno's `Writer` interface. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an asynchronous Writer, `false` otherwise. + +###### Category + +`I/O` + +#### Examples + +```ts +import { isWriter } from "jsr:@nick/is/writer"; + +isWriter(Deno.stdout); // true +isWriter(Deno.stderr); // true +isWriter(Deno.stdin); // false +``` + +## `Writer` + +An abstract interface which when implemented provides an interface to write +bytes from an array buffer to a file/resource asynchronously. + +###### Category + +`I/O` + +### Methods + +#### write + +```ts +write( + p: Uint8Array, + ): Promise; +``` + +Writes `p.byteLength` bytes from `p` to the underlying data stream. It resolves +to the number of bytes written from `p` (`0` <= `n` <= `p.byteLength`) or reject +with the error encountered that caused the write to stop early. `write()` must +reject with a non-null error if would resolve to `n` < `p.byteLength`. `write()` +must not modify the slice data, even temporarily. + +This function is one of the lowest level APIs and most users should not work +with this directly, but rather use +[`writeAll()`](https://deno.land/std/streams/write_all.ts?s=writeAll) from +`std/streams/write_all.ts` instead. + +Implementations should not retain a reference to `p`. + +--- From f5082f134c4d099a1434da34ad268911be467e7c Mon Sep 17 00:00:00 2001 From: Nicholas Berlette Date: Sat, 21 Jun 2025 06:58:27 +0000 Subject: [PATCH 07/24] chore(docs): add nojekyll and gitignore files --- docs/.gitignore | 11 +++++++++++ docs/.nojekyll | 0 2 files changed, 11 insertions(+) create mode 100644 docs/.gitignore create mode 100644 docs/.nojekyll diff --git a/docs/.gitignore b/docs/.gitignore new file mode 100644 index 0000000..9b79610 --- /dev/null +++ b/docs/.gitignore @@ -0,0 +1,11 @@ +cache +dist +.cache +.env* +Thumbs.db +.DS_Store +.Spotlight-V100 +.Trashes +node_modules +.deno +.npm diff --git a/docs/.nojekyll b/docs/.nojekyll new file mode 100644 index 0000000..e69de29 From 808d814e195883772dcef36ab542dea3faac1991 Mon Sep 17 00:00:00 2001 From: Nicholas Berlette Date: Thu, 10 Jul 2025 12:47:33 +0000 Subject: [PATCH 08/24] fix(docs): update examples in string-iterator and writable-stream --- docs/.vitepress/config.mts | 471 +++++++++++++++++++++++++++++++++ docs/.vitepress/theme/index.ts | 12 + docs/string-iterator.md | 5 +- docs/writable-stream.md | 2 +- src/string_iterator.ts | 27 +- src/writable_stream.ts | 2 +- 6 files changed, 508 insertions(+), 11 deletions(-) create mode 100644 docs/.vitepress/config.mts create mode 100644 docs/.vitepress/theme/index.ts diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts new file mode 100644 index 0000000..0d0c4fd --- /dev/null +++ b/docs/.vitepress/config.mts @@ -0,0 +1,471 @@ +import { transformerTwoslash } from "@shikijs/vitepress-twoslash"; +import { + createFileSystemTypesCache, +} from "@shikijs/vitepress-twoslash/cache-fs"; +import { defineConfig } from "vitepress"; +// import { expandGlobSync } from "@std/fs/expand-glob"; + +// const allNamedExports = await Deno.readTextFile("../mod.ts").then((text) => { +// const exports = text.match(/export\s+\{((?:(?!\})[\s\S])*?(?=\}))\}/); +// if (!exports?.[1]) return []; +// return exports[1].split(/[\s\n]*,[\s\n]*/).map((e) => e.trim()).map((e) => { +// if (e.includes(" as ")) { +// const [orig, alias] = e.split(/\s+as\s+/); +// return (alias === "default" ? `${alias} as ${orig}` : alias).trim(); +// } +// return e; +// }); +// }); + +// // const isNamespace = await Deno.readTextFile("../namespace.ts").then((text) => { +// // const exports = text.match(/export\s+({[^}]+})/g)?.[1]; +// // if (!exports) return "{}"; +// // return exports; +// // }); + +// const allTypeExports = await Deno.readTextFile("../src/namespace_types.ts").then((text) => { +// const exports = text.match(/export\s+type\s+\{((?:(?!\})[\s\S])*?(?=\}))\}/); +// if (!exports?.[1]) return []; +// return exports[1].split(/[\s\n]*,[\s\n]*/).map((e) => e.trim()).map((e) => { +// if (e.includes(" as ")) { +// const [orig, alias] = e.split(/\s+as\s+/); +// return (alias === "default" ? `${alias} as ${orig}` : alias).trim(); +// } +// return e; +// }); +// }); + +// const seen = new Set(); + +// const extraFiles = { +// // ensure "@nick/is" is always in the context for twoslash. +// // since this is a deno module by default, we do some trickery to +// // ensure the types are always available here. +// "./mod.ts": Deno.readTextFileSync("../mod.ts"), +// ...Iterator.from(expandGlobSync("../src/**/*.ts")).filter(( +// { isFile, path }, +// ) => +// isFile && !path.endsWith("test.ts") && +// !path.endsWith("bench.ts") +// ).reduce( +// (acc, { name, path }) => { +// // const key = path.replace(Deno.cwd(), "./").replace(/^(\.{1,2}\/)+/, "./"); +// const base = name.replace(/\.ts$/, "").replace(/(?<=[a-z0-9])_/g, "-"); +// const key = "./" + path.slice(Deno.cwd().split(/[\\/]/g).slice(0, -1).join("/").length + 1); +// const key2 = `@nick/is${base === "mod" ? "" : "/" + base}`; +// const prepend = Deno.readTextFileSync(path); + +// acc[key] = { prepend }; + +// const namedExports = +// prepend.match(/export\s+\{((?:(?!\})[\s\S])*?(?=\}))\}/)?.[1]?.split(/[\s\n]*,[\s\n]*/).map( +// (e) => e.trim(), +// ).map((e) => { +// if (e.includes(" as ")) { +// const [orig, alias] = e.split(/\s+as\s+/); +// return (alias === "default" ? `${alias} as ${orig}` : alias).trim(); +// } +// return e; +// }) ?? []; +// const typeExports = +// prepend.match(/export\s+type\s+\{((?:(?!\})[\s\S])*?(?=\}))\}/)?.[1]?.split( +// /[\s\n]*,[\s\n]*/, +// ).map((e) => e.trim()).map((e) => { +// if (e.includes(" as ")) { +// const [orig, alias] = e.split(/\s+as\s+/); +// return (alias === "default" ? `${alias} as ${orig}` : alias).trim(); +// } +// return e; +// }) ?? []; + +// // for (const arr of [namedExports, typeExports] as const) { +// // for (let i = 0; i < arr.length; i++) { +// // const x = arr[i]; +// // if (seen.has(x)) { +// // arr.splice(i, 1); +// // } else { +// // seen.add(x); +// // } +// // } +// // } + +// acc["./is.d.ts"].prepend += ` +// declare module "${key2}" { +// import {${namedExports}} from "${key}"; +// import type {${typeExports}} from "${key}"; + +// export {${namedExports}}; +// export type {${typeExports}}; +// } +// declare module "jsr:${key2}" { +// export * from "${key2}"; +// } +// `; +// return acc; +// }, +// { +// "./deno.d.ts": Deno.readTextFileSync("./deno.d.ts"), +// "./is.d.ts": { +// prepend: ` +// import * as is from "./namespace.ts"; + +// declare module "@nick/is" { +// export {${allNamedExports}} from "./mod.ts"; +// export type {${allTypeExports}} from "./types.ts"; +// export { is, is as default }; +// } + +// declare module "jsr:@nick/is" { +// export {${allNamedExports}} from "./mod.ts"; +// export type {${allTypeExports}} from "./types.ts"; +// export { is, is as default }; +// } +// `, +// }, +// // deno-lint-ignore no-explicit-any +// } as any, +// ), +// }; +const extraFiles = {}; + +// await Deno.writeTextFile("./vfs.json", JSON.stringify(extraFiles, null, 2)); + +// console.log(Object.fromEntries(Object.entries(extraFiles).slice(0, 3))); + +export default defineConfig({ + markdown: { + codeTransformers: [ + transformerTwoslash({ + typesCache: createFileSystemTypesCache(), + explicitTrigger: false, + twoslashOptions: { + extraFiles, + vfsRoot: "../", + handbookOptions: { + noErrorsCutted: true, + // noErrors: true, + }, + compilerOptions: { + strict: true, + noEmit: true, + skipLibCheck: true, + noUncheckedIndexedAccess: true, + noImplicitAny: true, + noImplicitThis: true, + noImplicitOverride: true, + noImplicitReturns: true, + noFallthroughCasesInSwitch: true, + noUnusedLocals: true, + noUnusedParameters: true, + allowImportingTsExtensions: true, + allowArbitraryExtensions: true, + moduleResolution: 100, + moduleSuffixes: [".js", ".ts"], + target: 99, + module: 99, + baseUrl: "../", + paths: { + "@nick/is/*": ["./src/*"], + "@nick/is": ["./src/mod.ts"], + "jsr:@nick/is/*": ["./src/*"], + "jsr:@nick/is": ["./src/mod.ts"], + }, + }, + }, + }), + ], + languages: ["js", "jsx", "ts", "tsx"], + }, + title: "@nick/is", + description: "Platform-agnostic. Performant. Portable. Predicates.", + themeConfig: { + // https://vitepress.dev/reference/default-theme-config + nav: [ + { text: "Home", link: "/" }, + { text: "Type Guards", link: "/#type-guards" }, + { text: "Examples", link: "/#examples" }, + ], + sidebar: [ + { + text: "Type Guards", + items: [ + { + text: "Primitives", + items: [ + { text: "isPrimitive", link: "/primitive" }, + { text: "isNull", link: "/null" }, + { text: "isUndefined", link: "/undefined" }, + { text: "isMissing", link: "/missing" }, + { text: "isPresent", link: "/present" }, + { text: "isPrintable", link: "/printable" }, + { text: "isPropertyKey", link: "/property-key" }, + { text: "isString", link: "/string" }, + { text: "isNumber", link: "/number" }, + { text: "isBigInt", link: "/bigint" }, + { text: "isBoolean", link: "/boolean" }, + { text: "isSymbol", link: "/symbol" }, + { text: "isRegisteredSymbol", link: "/registered-symbol" }, + { text: "isWellKnownSymbol", link: "/well-known-symbol" }, + { text: "isUniqueSymbol", link: "/unique-symbol" }, + { text: "isURLString", link: "/url-string" }, + { text: "isDateString", link: "/date-string" }, + { text: "isSemVer", link: "/semver" }, + { text: "isBoxedPrimitive", link: "/boxed-primitive" }, + { text: "isStringObject", link: "/string-object" }, + { text: "isNumberObject", link: "/number-object" }, + { text: "isBigIntObject", link: "/bigint-object" }, + { text: "isBooleanObject", link: "/boolean-object" }, + { text: "isSymbolObject", link: "/symbol-object" }, + { text: "isIdentifier", link: "/identifier" }, + { text: "isDefined", link: "/defined" }, + { text: "isFalsy", link: "/falsy" }, + { text: "isTruthy", link: "/truthy" }, + ], + }, + { + text: "Numbers", + link: "/number/number", + items: [ + { text: "isEven", link: "/number/even" }, + { text: "isOdd", link: "/number/odd" }, + { text: "isFiniteInteger", link: "/number/finite-integer" }, + { text: "isFiniteNumber", link: "/number/finite" }, + { text: "isFloat", link: "/number/float" }, + { text: "isFloat16", link: "/number/float16" }, + { text: "isFloat32", link: "/number/float32" }, + { text: "isFloat64", link: "/number/float64" }, + { text: "isInRange", link: "/number/in-range" }, + { text: "isInteger", link: "/number/integer" }, + { text: "isInt8", link: "/number/int8" }, + { text: "isInt16", link: "/number/int16" }, + { text: "isInt32", link: "/number/int32" }, + { text: "isUint8", link: "/number/uint8" }, + { text: "isUint16", link: "/number/uint16" }, + { text: "isUint32", link: "/number/uint32" }, + { text: "isNaN", link: "/number/nan" }, + { text: "isNegative", link: "/number/negative" }, + { text: "isNegativeZero", link: "/number/negative-zero" }, + { + text: "isNegativeFiniteInteger", + link: "/number/negative-finite-integer", + }, + { + text: "isNegativeFiniteNumber", + link: "/number/negative-finite", + }, + { text: "isNegativeInteger", link: "/number/negative-integer" }, + { + text: "isNegativeNonZeroFiniteInteger", + link: "/number/negative-nonzero-finite-integer", + }, + { + text: "isNegativeNonZeroFiniteNumber", + link: "/number/negative-nonzero-finite", + }, + { + text: "isNegativeNonZeroInteger", + link: "/number/negative-nonzero-integer", + }, + { + text: "isNegativeNonZeroNumber", + link: "/number/negative-nonzero", + }, + { + text: "isNonZeroFiniteInteger", + link: "/number/nonzero-finite-integer", + }, + { text: "isNonZeroFiniteNumber", link: "/number/nonzero-finite" }, + { text: "isNonZeroInteger", link: "/number/nonzero-integer" }, + { text: "isNonZeroNumber", link: "/number/nonzero" }, + { text: "isNumber", link: "/number/number" }, + { text: "isPositive", link: "/number/positive" }, + { + text: "isPositiveFiniteInteger", + link: "/number/positive-finite-integer", + }, + { + text: "isPositiveFiniteNumber", + link: "/number/positive-finite", + }, + { text: "isPositiveInteger", link: "/number/positive-integer" }, + { + text: "isPositiveNonZeroFiniteInteger", + link: "/number/positive-nonzero-finite-integer", + }, + { + text: "isPositiveNonZeroFiniteNumber", + link: "/number/positive-nonzero-finite", + }, + { + text: "isPositiveNonZeroInteger", + link: "/number/positive-nonzero-integer", + }, + { + text: "isPositiveNonZeroNumber", + link: "/number/positive-nonzero", + }, + { text: "isPositiveZero", link: "/number/positive-zero" }, + { text: "isZero", link: "/number/zero" }, + ], + }, + { + text: "Control Flow", + items: [ + { text: "isAsyncFunction", link: "/async-function" }, + { text: "isAsyncGenerator", link: "/async-generator" }, + { + text: "isAsyncGeneratorFunction", + link: "/async-generator-function", + }, + { text: "isAsyncIterable", link: "/async-iterable" }, + { text: "isAsyncIterator", link: "/async-iterator" }, + { + text: "isAsyncIterableIterator", + link: "/async-iterable-iterator", + }, + { text: "isAsyncIterableObject", link: "/async-iterable-object" }, + { text: "isPromise", link: "/promise" }, + { text: "isPromiseLike", link: "/promise-like" }, + ], + }, + { + text: "Iteration", + items: [ + { text: "isIterable", link: "/iterable" }, + { text: "isIterator", link: "/iterator" }, + { text: "isIterableIterator", link: "/iterable-iterator" }, + { text: "isIterableObject", link: "/iterable-object" }, + { text: "isArrayIterator", link: "/array-iterator" }, + { text: "isSetIterator", link: "/set-iterator" }, + { text: "isMapIterator", link: "/map-iterator" }, + { text: "isStringIterator", link: "/string-iterator" }, + { text: "isGenerator", link: "/generator" }, + { text: "isGeneratorFunction", link: "/generator-function" }, + ], + }, + { + text: "Indexed Collections", + items: [ + { text: "isArray", link: "/array" }, + { text: "isArrayLike", link: "/array-like" }, + { text: "isArrayLikeObject", link: "/array-like-object" }, + { text: "isArguments", link: "/arguments" }, + ], + }, + { + text: "Keyed Collections", + items: [ + { text: "isMap", link: "/map" }, + { text: "isMapLike", link: "/map-like" }, + { text: "isSet", link: "/set" }, + { text: "isSetLike", link: "/set-like" }, + { text: "isExtendedSetLike", link: "/extended-set-like" }, + { text: "isReadonlySetLike", link: "/readonly-set-like" }, + { text: "isReadonlyCollection", link: "/readonly-collection" }, + ], + }, + { + text: "Weak Collections", + items: [ + { text: "isWeakMap", link: "/weak-map" }, + { text: "isWeakSet", link: "/weak-set" }, + { text: "isWeakRef", link: "/weak-ref" }, + { text: "isWeakKey", link: "/weak-key" }, + ], + }, + { + text: "Objects", + items: [ + { text: "isClass", link: "/class" }, + { text: "isConstructor", link: "/constructor" }, + { text: "isFunction", link: "/function" }, + { text: "isKeyOf", link: "/keyof" }, + { text: "isInstance", link: "/instance" }, + { text: "isNonArrayObject", link: "/non-array-object" }, + { text: "isObject", link: "/object" }, + { text: "isObjectLike", link: "/object-like" }, + { text: "isPlainObject", link: "/plain-object" }, + { text: "isEmptyObject", link: "/empty-object" }, + { text: "isEnum", link: "/enum" }, + { text: "isEnumLike", link: "/enum" }, + { text: "isError", link: "/error" }, + { text: "isRegExp", link: "/regexp" }, + { text: "isDate", link: "/date" }, + { text: "isTagged", link: "/tagged" }, + { text: "isTemplateObject", link: "/template-object" }, + { + text: "isTemplateStringsArray", + link: "/template-strings-array", + }, + ], + }, + { + text: "Structured Data", + items: [ + { text: "isArrayBuffer", link: "/array-buffer" }, + { text: "isSharedArrayBuffer", link: "/shared-array-buffer" }, + { text: "isArrayBufferLike", link: "/array-buffer-like" }, + { text: "isArrayBufferView", link: "/array-buffer-view" }, + { text: "isBufferSource", link: "/buffer-source" }, + { text: "isDataView", link: "/data-view" }, + { text: "isTypedArray", link: "/typed-array" }, + { text: "isUint8Array", link: "/uint8-array" }, + { text: "isUint8ClampedArray", link: "/uint8-clamped-array" }, + { text: "isUint16Array", link: "/uint16-array" }, + { text: "isUint32Array", link: "/uint32-array" }, + { text: "isInt8Array", link: "/int8-array" }, + { text: "isInt16Array", link: "/int16-array" }, + { text: "isInt32Array", link: "/int32-array" }, + { text: "isFloat16Array", link: "/float16-array" }, + { text: "isFloat32Array", link: "/float32-array" }, + { text: "isFloat64Array", link: "/float64-array" }, + { text: "isBigInt64Array", link: "/bigint64-array" }, + { text: "isBigUint64Array", link: "/biguint64-array" }, + ], + }, + { + text: "Web APIs", + items: [ + { text: "isReadableStream", link: "/readable-stream" }, + { text: "isWritableStream", link: "/writable-stream" }, + { text: "isURL", link: "/url" }, + { text: "isURLPattern", link: "/url-pattern" }, + { text: "isURLSearchParams", link: "/url-search-params" }, + ], + }, + { + text: "Explicit Resource Management", + items: [ + { text: "isDisposable", link: "/disposable" }, + { text: "isAsyncDisposable", link: "/async-disposable" }, + ], + }, + { + text: "Deno I/O", + items: [ + { text: "isCloser", link: "/closer" }, + { text: "isReader", link: "/reader" }, + { text: "isWriter", link: "/writer" }, + { text: "isReaderSync", link: "/reader-sync" }, + { text: "isWriterSync", link: "/writer-sync" }, + { text: "isSeeker", link: "/seeker" }, + { text: "isSeekerSync", link: "/seeker-sync" }, + ], + }, + { + text: "Composition", + items: [ + { text: "both", link: "/both" }, + { text: "either", link: "/either" }, + ], + }, + ], + }, + ], + socialLinks: [ + { icon: "github", link: "https://github.com/nberlette/is#readme" }, + { icon: "jsr", link: "https://jsr.io/@nick/is/doc" }, + { icon: "npm", link: "https://www.npmjs.com/package/@nickb/is" }, + ], + }, +}); diff --git a/docs/.vitepress/theme/index.ts b/docs/.vitepress/theme/index.ts new file mode 100644 index 0000000..6f1ff11 --- /dev/null +++ b/docs/.vitepress/theme/index.ts @@ -0,0 +1,12 @@ +import type { EnhanceAppContext } from "vitepress"; +import TwoslashFloatingVue from "@shikijs/vitepress-twoslash/client"; +import Theme from "vitepress/theme"; + +import "@shikijs/vitepress-twoslash/style.css"; + +export default { + extends: Theme, + enhanceApp({ app }: EnhanceAppContext) { + app.use(TwoslashFloatingVue); + }, +}; diff --git a/docs/string-iterator.md b/docs/string-iterator.md index 1e4f345..269b429 100644 --- a/docs/string-iterator.md +++ b/docs/string-iterator.md @@ -34,9 +34,10 @@ is the type of object returned by `String.prototype[Symbol.iterator]`. import { isStringIterator } from "jsr:@nick/is/string-iterator"; const str = "foo"; -const iter = str[Symbol.iterator](); -console.log(isStringIterator(iterator)); // true console.log(isStringIterator(str)); // false + +const iter = str[Symbol.iterator](); +console.log(isStringIterator(iter)); // true ``` ## `StringIterator` diff --git a/docs/writable-stream.md b/docs/writable-stream.md index 939e888..2d9bd97 100644 --- a/docs/writable-stream.md +++ b/docs/writable-stream.md @@ -28,7 +28,7 @@ Checks if [it](#it "Jump to symbol: 'it'") is a `WritableStream` object. ```ts import { isWritableStream } from "jsr:@nick/is/writable-stream"; -a; + const stream = new WritableStream(); isWritableStream(stream); // true diff --git a/src/string_iterator.ts b/src/string_iterator.ts index 5986f24..e208e24 100644 --- a/src/string_iterator.ts +++ b/src/string_iterator.ts @@ -16,18 +16,30 @@ * import { isStringIterator } from "jsr:@nick/is/string-iterator"; * * const str = "foo"; - * const iter = str[Symbol.iterator](); - * console.log(isStringIterator(iterator)); // true * console.log(isStringIterator(str)); // false + * + * const iter = str[Symbol.iterator](); + * console.log(isStringIterator(iter)); // true * ``` - * @category Iterables + * @category Iteration * @module string-iterator */ import { isIterator } from "./iterator.ts"; import { isTagged } from "./tagged.ts"; -/** Represents a string iterator. */ +/** + * Represents an iterator object that iterates over one or more characters from + * a given string. + * + * This is the type returned by the native `[Symbol.iterator]` method on the + * `String.prototype` object, to iterate over a string's characters one-by-one. + * + * @category Iteration + * @tags String, Iterator + * @template T The type of string being iterated over, defaults to `string`. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator + */ export interface StringIterator extends IteratorObject { readonly [Symbol.toStringTag]: "String Iterator"; @@ -45,11 +57,12 @@ export interface StringIterator * import { isStringIterator } from "jsr:@nick/is/string-iterator"; * * const str = "foo"; - * const iter = str[Symbol.iterator](); - * console.log(isStringIterator(iterator)); // true * console.log(isStringIterator(str)); // false + * + * const iter = str[Symbol.iterator](); + * console.log(isStringIterator(iter)); // true * ``` - * @category Iterables + * @category Iteration * @tags String, Iterator */ export function isStringIterator( diff --git a/src/writable_stream.ts b/src/writable_stream.ts index c701c4f..d849c99 100644 --- a/src/writable_stream.ts +++ b/src/writable_stream.ts @@ -14,7 +14,7 @@ import { isObject } from "./object.ts"; * @example * ```ts * import { isWritableStream } from "jsr:@nick/is/writable-stream"; - * a + * * const stream = new WritableStream(); * isWritableStream(stream); // true * From 78c758bce762ab8e830a54b1c83e601051353f60 Mon Sep 17 00:00:00 2001 From: Nicholas Berlette Date: Wed, 9 Jul 2025 19:11:32 +0000 Subject: [PATCH 09/24] chore(internal): rename src/_internal to src/internal Happy 32nd birthday to me! --- src/_internal/primordials.ts | 127 --- src/{_internal => internal}/expect_type.ts | 2 +- src/internal/fail.ts | 34 + src/{_internal => internal}/global_this.ts | 3 +- src/{_internal => internal}/has_methods.ts | 2 +- .../is_tagged_native.ts | 14 +- src/internal/primordials.ts | 919 ++++++++++++++++++ src/{_internal => internal}/to_string.ts | 14 +- src/internal/try_getter.ts | 50 + src/{_internal => internal}/try_method.ts | 2 +- src/{_internal => internal}/try_value_of.ts | 2 +- src/{_internal => internal}/types.ts | 21 +- src/internal/uncurry_getter.ts | 101 ++ .../uncurry_setter.ts} | 24 +- src/{_internal => internal}/uncurry_this.ts | 2 +- src/{_internal => internal}/unicode_regexp.ts | 2 +- 16 files changed, 1159 insertions(+), 160 deletions(-) delete mode 100644 src/_internal/primordials.ts rename src/{_internal => internal}/expect_type.ts (76%) create mode 100644 src/internal/fail.ts rename src/{_internal => internal}/global_this.ts (95%) rename src/{_internal => internal}/has_methods.ts (95%) rename src/{_internal => internal}/is_tagged_native.ts (84%) create mode 100644 src/internal/primordials.ts rename src/{_internal => internal}/to_string.ts (60%) create mode 100644 src/internal/try_getter.ts rename src/{_internal => internal}/try_method.ts (93%) rename src/{_internal => internal}/try_value_of.ts (90%) rename src/{_internal => internal}/types.ts (81%) create mode 100644 src/internal/uncurry_getter.ts rename src/{_internal/uncurry_getter.ts => internal/uncurry_setter.ts} (70%) rename src/{_internal => internal}/uncurry_this.ts (81%) rename src/{_internal => internal}/unicode_regexp.ts (99%) diff --git a/src/_internal/primordials.ts b/src/_internal/primordials.ts deleted file mode 100644 index cc0efef..0000000 --- a/src/_internal/primordials.ts +++ /dev/null @@ -1,127 +0,0 @@ -// deno-lint-ignore-file no-explicit-any -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/primordials - */ -import { $globalThis } from "./global_this.ts"; -import type * as T from "./types.ts"; - -export const Array: ArrayConstructor = $globalThis.Array; -export const String: StringConstructor = $globalThis.String; -export const Number: NumberConstructor = $globalThis.Number; -export const Boolean: BooleanConstructor = $globalThis.Boolean; -export const Date: DateConstructor = $globalThis.Date; -export const RegExp: RegExpConstructor = $globalThis.RegExp; - -export const Object: ObjectConstructor = $globalThis.Object; -export const ObjectPrototype: Object = Object.prototype; -export const ObjectKeys: (o: O) => T.ObjectKeys = Object.keys; -export const ObjectValues: (o: O) => T.ObjectValues = Object.values; -export const ObjectEntries: (o: O) => T.ObjectEntries = Object.entries; -export const ObjectGetPrototypeOf: (o: any) => any = Object.getPrototypeOf; -export const ObjectGetOwnPropertyDescriptor: ( - o: O, - k: K, -) => - | ( - & TypedPropertyDescriptor - & ThisType - ) - | undefined = Object.getOwnPropertyDescriptor; - -export const Symbol: SymbolConstructor = $globalThis.Symbol; -export const SymbolFor: typeof Symbol.for = Symbol.for; -export const SymbolKeyFor: typeof Symbol.keyFor = Symbol.keyFor; -export const SymbolToStringTag: SymbolToStringTag = Symbol.toStringTag; -export type SymbolToStringTag = typeof Symbol.toStringTag; -export const SymbolIterator: SymbolIterator = Symbol.iterator; -export type SymbolIterator = typeof Symbol.iterator; -export const SymbolAsyncIterator: SymbolAsyncIterator = Symbol.asyncIterator; -export type SymbolAsyncIterator = typeof Symbol.asyncIterator; -export const SymbolHasInstance: SymbolHasInstance = Symbol.hasInstance; -export type SymbolHasInstance = typeof Symbol.hasInstance; -export const SymbolDispose: SymbolDispose = Symbol.dispose; -export type SymbolDispose = typeof Symbol.dispose; -export const SymbolAsyncDispose: SymbolAsyncDispose = Symbol.asyncDispose; -export type SymbolAsyncDispose = typeof Symbol.asyncDispose; -export const SymbolMetadata: SymbolMetadata = Symbol.metadata; -export type SymbolMetadata = typeof Symbol.metadata; -export const SymbolIsConcatSpreadable: SymbolIsConcatSpreadable = Symbol - .isConcatSpreadable; -export type SymbolIsConcatSpreadable = typeof Symbol.isConcatSpreadable; - -export const Function: FunctionConstructor = $globalThis.Function; -export const FunctionPrototype: Function = Function.prototype; -export type FunctionPrototype = typeof Function.prototype; - -export const { - bind, - call, - apply, - toString, - [SymbolHasInstance]: hasInstance, -} = FunctionPrototype; - -export const uncurryThis = bind.bind(call) as < - T, - const A extends readonly unknown[], - R = unknown, ->(fn: (this: T, ...args: A) => R) => (target: T, ...args: A) => R; - -export const FunctionPrototypeBind = uncurryThis( - bind as CallableFunction["bind"], -); -export const FunctionPrototypeCall = uncurryThis( - call as CallableFunction["call"], -); -export const FunctionPrototypeApply = uncurryThis( - apply as CallableFunction["apply"], -); -export const FunctionPrototypeToString = uncurryThis( - toString as CallableFunction["toString"], -); -export const FunctionPrototypeHasInstance = uncurryThis( - hasInstance as CallableFunction[SymbolHasInstance], -); - -export const Error: ErrorConstructor = $globalThis.Error; -export const ErrorCaptureStackTrace: typeof Error.captureStackTrace = - Error.captureStackTrace; -export const TypeError: TypeErrorConstructor = $globalThis.TypeError; -export const ReferenceError: ReferenceErrorConstructor = - $globalThis.ReferenceError; -export const SyntaxError: SyntaxErrorConstructor = $globalThis.SyntaxError; -export const RangeError: RangeErrorConstructor = $globalThis.RangeError; -export const EvalError: EvalErrorConstructor = $globalThis.EvalError; -export const URIError: URIErrorConstructor = $globalThis.URIError; - -export const Reflect: typeof $globalThis.Reflect = $globalThis.Reflect; -export const Atomics: typeof $globalThis.Atomics = $globalThis.Atomics; - -export const Proxy: ProxyConstructor = $globalThis.Proxy; -export const Set: SetConstructor = $globalThis.Set; -export const Map: MapConstructor = $globalThis.Map; -export const WeakMap: WeakMapConstructor = $globalThis.WeakMap; -export const WeakSet: WeakSetConstructor = $globalThis.WeakSet; -export const WeakRef: WeakRefConstructor = $globalThis.WeakRef; - -export const ArrayBuffer: ArrayBufferConstructor = $globalThis.ArrayBuffer; -export const SharedArrayBuffer: SharedArrayBufferConstructor = - $globalThis.SharedArrayBuffer; -export const DataView: DataViewConstructor = $globalThis.DataView; -export const Int8Array: Int8ArrayConstructor = $globalThis.Int8Array; -export const Int16Array: Int16ArrayConstructor = $globalThis.Int16Array; -export const Int32Array: Int32ArrayConstructor = $globalThis.Int32Array; -export const Uint8Array: Uint8ArrayConstructor = $globalThis.Uint8Array; -export const Uint8ClampedArray: Uint8ClampedArrayConstructor = - $globalThis.Uint8ClampedArray; -export const Uint16Array: Uint16ArrayConstructor = $globalThis.Uint16Array; -export const Uint32Array: Uint32ArrayConstructor = $globalThis.Uint32Array; -export const Float16Array: Float16ArrayConstructor = $globalThis.Float16Array; -export const Float32Array: Float32ArrayConstructor = $globalThis.Float32Array; -export const Float64Array: Float64ArrayConstructor = $globalThis.Float64Array; -export const BigInt64Array: BigInt64ArrayConstructor = - $globalThis.BigInt64Array; -export const BigUint64Array: BigUint64ArrayConstructor = - $globalThis.BigUint64Array; diff --git a/src/_internal/expect_type.ts b/src/internal/expect_type.ts similarity index 76% rename from src/_internal/expect_type.ts rename to src/internal/expect_type.ts index f2997ff..30989c9 100644 --- a/src/_internal/expect_type.ts +++ b/src/internal/expect_type.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/expect-type + * @see https://jsr.io/@nick/is/doc/internal/expect-type */ export const expectType: (value: T) => void = (_) => {}; diff --git a/src/internal/fail.ts b/src/internal/fail.ts new file mode 100644 index 0000000..521a2d1 --- /dev/null +++ b/src/internal/fail.ts @@ -0,0 +1,34 @@ +// deno-lint-ignore-file ban-types +/*! + * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. + * @license MIT (https://nick.mit-license.org/2024) + * @see https://jsr.io/@nick/is/doc/internal/fail + */ +/** + * @module fail + */ +import { Error, ErrorCaptureStackTrace } from "./primordials.ts"; + +/** + * Throws an error with the given message and captures the stack trace. + * + * Optionally, you can provide a function to trim the stack trace to a specific + * function call site, via the `stackCrawlMark` parameter. This can be useful + * for debugging purposes and removing unnecessary frames or implementation + * details from the stack trace. + * + * @param message - The error message or an Error object to throw. + * @param stackCrawlMark - A function to mark the point in the stack trace to + * start capturing the stack trace. This is useful for debugging. + * @throws {Error} - Throws an error with the provided message. + */ +export function fail( + message?: string | Error, + stackCrawlMark?: Function, +): never { + message ??= "Unknown error"; + const error = typeof message === "string" ? new Error(message) : message; + ErrorCaptureStackTrace?.(error, stackCrawlMark ?? fail); + error.stack; // force stack trace to be generated + throw error; +} diff --git a/src/_internal/global_this.ts b/src/internal/global_this.ts similarity index 95% rename from src/_internal/global_this.ts rename to src/internal/global_this.ts index 6fb621b..cbe4a16 100644 --- a/src/_internal/global_this.ts +++ b/src/internal/global_this.ts @@ -1,8 +1,9 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/global-this + * @see https://jsr.io/@nick/is/doc/internal/global-this */ + declare const root: typeof globalThis | undefined; declare const self: typeof globalThis | undefined; declare const window: typeof globalThis | undefined; diff --git a/src/_internal/has_methods.ts b/src/internal/has_methods.ts similarity index 95% rename from src/_internal/has_methods.ts rename to src/internal/has_methods.ts index 8aded15..3585056 100644 --- a/src/_internal/has_methods.ts +++ b/src/internal/has_methods.ts @@ -2,7 +2,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/has-methods + * @see https://jsr.io/@nick/is/doc/internal/has-methods */ import { Object } from "./primordials.ts"; diff --git a/src/_internal/is_tagged_native.ts b/src/internal/is_tagged_native.ts similarity index 84% rename from src/_internal/is_tagged_native.ts rename to src/internal/is_tagged_native.ts index 4f150b1..13ada72 100644 --- a/src/_internal/is_tagged_native.ts +++ b/src/internal/is_tagged_native.ts @@ -2,10 +2,14 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/is-tagged-native + * @see https://jsr.io/@nick/is/doc/internal/is-tagged-native */ -import { Object, SymbolToStringTag } from "./primordials.ts"; +import { + Object, + StringPrototypeReplace, + SymbolToStringTag, +} from "./primordials.ts"; import { toString } from "./to_string.ts"; /** @@ -30,7 +34,11 @@ export function isTaggedNative( tag: T, allowCustom?: boolean, ): boolean { - tag = tag.toString().replace(/^\[object (.+)\]$/, "$1") as T; + tag = StringPrototypeReplace( + (tag ?? "") + "", + /^\[object (.+)\]$/, + (_, t) => t, + ) as T; return toString(it = Object(it)) === `[object ${tag}]` && (allowCustom ? SymbolToStringTag in it && it[SymbolToStringTag] === tag diff --git a/src/internal/primordials.ts b/src/internal/primordials.ts new file mode 100644 index 0000000..0de40d1 --- /dev/null +++ b/src/internal/primordials.ts @@ -0,0 +1,919 @@ +// deno-lint-ignore-file no-explicit-any no-var +/*! + * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. + * @license MIT (https://nick.mit-license.org/2024) + * @see https://jsr.io/@nick/is/doc/internal/primordials + */ + +import { $globalThis } from "./global_this.ts"; +import { fail } from "./fail.ts"; +import type * as T from "./types.ts"; +import { uncurryGetter } from "./uncurry_getter.ts"; +import { uncurrySetter } from "./uncurry_setter.ts"; + +// #region Symbol +/** + * Represents the `Symbol` constructor type. + * + * **Important**: Thanks to TypeScript's ridiculously strict rules surrounding + * the `Symbol` construct, it is impossible to create a `unique symbol` from + * this alias, despite the fact it is a direct alias to the global `Symbol`, + * sharing the same exact name, type, and properties. Therefore, to create a + * `unique symbol`, you'll have to do something like this: + * + * ```ts + * import { Symbol } from "./primordials.ts"; + * + * // you can also use `as any`, but I prefer `as never` to avoid lint errors. + * const kUser: unique symbol = Symbol("user") as never; + * ``` + */ +export var Symbol: SymbolConstructor = $globalThis.Symbol; + +/** + * @see {@linkcode Symbol} for notes on creating `unique symbol` types. + */ +export var SymbolFor: typeof Symbol.for = Symbol.for; +export var SymbolKeyFor: typeof Symbol.keyFor = Symbol.keyFor; + +export var SymbolToStringTag: SymbolToStringTag = Symbol.toStringTag; +export type SymbolToStringTag = typeof Symbol.toStringTag; + +export var SymbolIterator: SymbolIterator = Symbol.iterator; +export type SymbolIterator = typeof Symbol.iterator; + +export var SymbolAsyncIterator: SymbolAsyncIterator = Symbol.asyncIterator; +export type SymbolAsyncIterator = typeof Symbol.asyncIterator; + +export var SymbolHasInstance: SymbolHasInstance = Symbol.hasInstance; +export type SymbolHasInstance = typeof Symbol.hasInstance; + +export var SymbolDispose: SymbolDispose = Symbol.dispose; +export type SymbolDispose = typeof Symbol.dispose; + +export var SymbolAsyncDispose: SymbolAsyncDispose = Symbol.asyncDispose; +export type SymbolAsyncDispose = typeof Symbol.asyncDispose; + +export var SymbolMetadata: SymbolMetadata = Symbol.metadata; +export type SymbolMetadata = typeof Symbol.metadata; + +export var SymbolIsConcatSpreadable: SymbolIsConcatSpreadable = Symbol + .isConcatSpreadable; +export type SymbolIsConcatSpreadable = typeof Symbol.isConcatSpreadable; +// #endregion Symbol + +// #region Function +export var Function: FunctionConstructor = $globalThis.Function; +export var FunctionPrototype = Function.prototype; + +export var { + bind, + call, + apply, + toString: fnToString, + [SymbolHasInstance]: hasInstance, +} = FunctionPrototype; + +export type Uncurry = T extends + (this: infer ThisArg, ...args: infer A) => infer R + ? [[This], [void]] extends [[void], [This]] + ? (thisArg: ThisArg, ...args: A) => R + : (thisArg: This, ...args: A) => R + : T extends (...args: infer A) => infer R + ? (thisArg: [This] extends [void] ? unknown : This, ...args: A) => R + : never; + +export var uncurryThis: ( + fn: (this: T, ...args: A) => R, + _thisArg?: T, +) => (self: T, ...args: A) => R = bind.bind(call); + +export var FunctionPrototypeBind: < + T, + A extends readonly any[], + B extends readonly any[], + R, +>( + self: (this: T, ...args: [...A, ...B]) => R, + thisArg: T, + ...args: A +) => (...args: B) => R = uncurryThis(bind); + +export var FunctionPrototypeCall: ( + self: (this: T, ...args: A) => R, + thisArg: T, + ...args: A +) => R = uncurryThis(call as CallableFunction["call"]); + +export var FunctionPrototypeApply: ( + self: (this: T, ...args: A) => R, + thisArg: T, + args: A, +) => R = uncurryThis(apply); + +export var FunctionPrototypeToString = uncurryThis( + fnToString as CallableFunction["toString"], +); +export var FunctionPrototypeHasInstance = uncurryThis( + hasInstance as CallableFunction[SymbolHasInstance], +); +// #endregion Function + +// #region Object + +export var Object: ObjectConstructor = $globalThis.Object; +export type Object = globalThis.Object; +export var ObjectPrototype: Object = Object.prototype; +export var { toString } = ObjectPrototype; +export var ObjectKeys: (o: O) => T.ObjectKeys = Object.keys; +export type ObjectKeys = T.ObjectKeys; +export var ObjectValues: (o: O) => T.ObjectValues = Object.values; +export type ObjectValues = T.ObjectValues; +export var ObjectEntries: (o: O) => T.ObjectEntries = Object.entries; +export type ObjectEntries = T.ObjectEntries; +export var ObjectFromEntries: < + const E extends readonly (readonly [PropertyKey, any])[], +>(entries: E) => T.ObjectFromEntries = Object.fromEntries; +export var ObjectGetPrototypeOf: (o: any) => any = Object.getPrototypeOf; +export var ObjectGetOwnPropertyDescriptor: ( + o: O, + k: K, +) => + | ( + & TypedPropertyDescriptor + & ThisType + ) + | undefined = Object.getOwnPropertyDescriptor; + +export var ObjectFreeze: typeof Object.freeze = Object.freeze; +export var ObjectPrototypeToString: (o: any) => string = uncurryThis(toString); +export var ObjectCreate: typeof Object.create = Object.create; +export var ObjectDefineProperty: typeof Object.defineProperty = + Object.defineProperty; +export var ObjectGetOwnPropertyDescriptors: + typeof Object.getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors; +export var ObjectGetOwnPropertyNames: typeof Object.getOwnPropertyNames = + Object.getOwnPropertyNames; +export var ObjectGetOwnPropertySymbols: typeof Object.getOwnPropertySymbols = + Object.getOwnPropertySymbols; +export var ObjectSetPrototypeOf: typeof Object.setPrototypeOf = + Object.setPrototypeOf; +export var ObjectDefineProperties = Object.defineProperties || function (o, p) { + for (const k in p) { + if (ObjectHasOwn(p, k)) ObjectDefineProperty(o, k, p[k]); + } + return o; +}; +export var ObjectIs: typeof Object.is = Object.is || function (a, b) { + if (a === b) return a !== 0 || 1 / a === 1 / b; + return a !== a && b !== b; +}; + +export type ObjectHasOwn = { + ( + o: T, + p: K, + ): o is T & Record; + (o: object, p: PropertyKey): boolean; +}; +export var ObjectPrototypeHasOwnProperty: ObjectHasOwn = uncurryThis( + ObjectPrototype.hasOwnProperty, +) as ObjectHasOwn; + +export var ObjectHasOwn: ObjectHasOwn = (() => { + if (typeof Object.hasOwn === "function") return Object.hasOwn as ObjectHasOwn; + return ObjectPrototypeHasOwnProperty; +})(); + +// #endregion Object + +// #region Array + +export var Array: ArrayConstructor = $globalThis.Array; +export type Array = T[]; +// Array.from requires a `this` context, despite being a static method +export var ArrayFrom: typeof Array.from = FunctionPrototypeBind( + Array.from, + Array, +) as typeof Array.from; +export var ArrayFromAsync: typeof Array.fromAsync = FunctionPrototypeBind( + Array.fromAsync, + Array, +) as typeof Array.fromAsync; +export var ArrayIsArray: typeof Array.isArray = Array.isArray; +export var ArrayOf: (...items: T[]) => T[] = Array.of; +export var ArrayPrototype: Array = Array.prototype; +export var ArrayPrototypeToString = uncurryThis( + ArrayPrototype.toString, + ArrayPrototype, +); +export var ArrayPrototypeJoin = uncurryThis( + ArrayPrototype.join, + ArrayPrototype, +); +export var ArrayPrototypePop = uncurryThis( + ArrayPrototype.pop, + ArrayPrototype, +); +export var ArrayPrototypePush = uncurryThis( + ArrayPrototype.push, + ArrayPrototype, +); +export var ArrayPrototypeShift = uncurryThis( + ArrayPrototype.shift, + ArrayPrototype, +); +export var ArrayPrototypeUnshift = uncurryThis( + ArrayPrototype.unshift, + ArrayPrototype, +); +// #endregion Array + +// #region Date + +export var Date: DateConstructor = $globalThis.Date; +export var DateNow: typeof Date.now = Date.now; +export var DateParse: typeof Date.parse = Date.parse; +export var DateUTC: typeof Date.UTC = Date.UTC; +export var DatePrototype: Date = Date.prototype; +export var DatePrototypeGetTime: Uncurry = uncurryThis( + DatePrototype.getTime, +); +export var DatePrototypeToString: Uncurry = uncurryThis( + DatePrototype.toString, +); +export var DatePrototypeToISOString: Uncurry = + uncurryThis( + DatePrototype.toISOString, + ); +export var DatePrototypeToDateString: Uncurry = + uncurryThis( + DatePrototype.toDateString, + ); +export var DatePrototypeToTimeString: Uncurry = + uncurryThis( + DatePrototype.toTimeString, + ); +export var DatePrototypeToLocaleString: Uncurry = + uncurryThis( + DatePrototype.toLocaleString, + ); + +// #endregion Date + + +// #region RegExp +export var RegExp: RegExpConstructor = $globalThis.RegExp; +export var RegExpPrototype: RegExp = RegExp.prototype; +export var RegExpPrototypeCompile: Uncurry = + uncurryThis( + RegExpPrototype.compile, + ); +export var RegExpPrototypeGetHasIndices: (self: RegExp) => boolean = + uncurryGetter( + RegExpPrototype, + "hasIndices", + "stub", + ); +export var RegExpPrototypeGetGlobal: (self: RegExp) => boolean = uncurryGetter( + RegExpPrototype, + "global", + "stub", +); +export var RegExpPrototypeGetMultiline: (self: RegExp) => boolean = + uncurryGetter( + RegExpPrototype, + "multiline", + "stub", + ); +export var RegExpPrototypeGetIgnoreCase: (self: RegExp) => boolean = + uncurryGetter( + RegExpPrototype, + "ignoreCase", + "stub", + ); +export var RegExpPrototypeGetDotAll: (self: RegExp) => boolean = uncurryGetter( + RegExpPrototype, + "dotAll", + "stub", +); +export var RegExpPrototypeGetUnicode: (self: RegExp) => boolean = uncurryGetter( + RegExpPrototype, + "unicode", + "stub", +); +export var RegExpPrototypeGetUnicodeSets: (self: RegExp) => boolean = + uncurryGetter( + RegExpPrototype, + "unicodeSets", + "stub", + ); +export var RegExpPrototypeGetSticky: (self: RegExp) => boolean = uncurryGetter( + RegExpPrototype, + "sticky", + "stub", +); +export var RegExpPrototypeGetSource: (self: RegExp) => string = uncurryGetter( + RegExpPrototype, + "source", + "stub", +); +export var RegExpPrototypeGetFlags: (self: RegExp) => string = uncurryGetter( + RegExpPrototype, + "flags", + "stub", +); + +export var RegExpPrototypeTest: Uncurry = uncurryThis( + RegExpPrototype.test, +); +export var RegExpPrototypeExec: Uncurry = uncurryThis( + RegExpPrototype.exec, +); +export var RegExpPrototypeToString: Uncurry = + uncurryThis( + RegExpPrototype.toString, + ); +// #endregion RegExp + +// #region String +export var String: StringConstructor = $globalThis.String; +var { raw, fromCharCode, fromCodePoint } = String; + +export var StringRaw: typeof String.raw = raw; +export var StringFromCharCode: typeof String.fromCharCode = fromCharCode; +export var StringFromCodePoint: typeof String.fromCodePoint = fromCodePoint; + +export var StringPrototype: String = String.prototype; +export var StringPrototypeAt: Uncurry = uncurryThis( + StringPrototype.at, +); +export var StringPrototypeCharAt: Uncurry = + uncurryThis(StringPrototype.charAt); +export var StringPrototypeCharCodeAt: Uncurry = + uncurryThis(StringPrototype.charCodeAt); +export var StringPrototypeCodePointAt: Uncurry = + uncurryThis(StringPrototype.codePointAt); +export var StringPrototypeConcat: Uncurry = + uncurryThis(StringPrototype.concat); +export var StringPrototypeEndsWith: Uncurry = + uncurryThis(StringPrototype.endsWith); +export var StringPrototypeIncludes: Uncurry = + uncurryThis(StringPrototype.includes); +export var StringPrototypeIndexOf: Uncurry = + uncurryThis(StringPrototype.indexOf); +export var StringPrototypeIsWellFormed: Uncurry< + String["isWellFormed"], + string +> = uncurryThis(StringPrototype.isWellFormed); +export var StringPrototypeLastIndexOf: Uncurry = + uncurryThis(StringPrototype.lastIndexOf); +export var StringPrototypeLocaleCompare: Uncurry< + String["localeCompare"], + string +> = uncurryThis(StringPrototype.localeCompare); +export var StringPrototypeMatch: Uncurry = uncurryThis( + StringPrototype.match, +); +export var StringPrototypeMatchAll: Uncurry = + uncurryThis(StringPrototype.matchAll); +export var StringPrototypeNormalize: Uncurry = + uncurryThis(StringPrototype.normalize); +export var StringPrototypePadEnd: Uncurry = + uncurryThis(StringPrototype.padEnd); +export var StringPrototypePadStart: Uncurry = + uncurryThis(StringPrototype.padStart); +export var StringPrototypeRepeat: Uncurry = + uncurryThis(StringPrototype.repeat); +export var StringPrototypeReplace: Uncurry = + uncurryThis(StringPrototype.replace); +export var StringPrototypeReplaceAll: Uncurry = + uncurryThis(StringPrototype.replaceAll); +export var StringPrototypeSearch: Uncurry = + uncurryThis(StringPrototype.search); +export var StringPrototypeSlice: Uncurry = uncurryThis( + StringPrototype.slice, +); +export var StringPrototypeSplit: Uncurry = uncurryThis( + StringPrototype.split, +); +export var StringPrototypeStartsWith: Uncurry = + uncurryThis(StringPrototype.startsWith); +export var StringPrototypeSubstring: Uncurry = + uncurryThis(StringPrototype.substring); +export var StringPrototypeToLowerCase: Uncurry = + uncurryThis(StringPrototype.toLowerCase); +export var StringPrototypeToUpperCase: Uncurry = + uncurryThis(StringPrototype.toUpperCase); +export var StringPrototypeToLocaleLowerCase: Uncurry< + String["toLocaleLowerCase"], + string +> = uncurryThis(StringPrototype.toLocaleLowerCase); +export var StringPrototypeToLocaleUpperCase: Uncurry< + String["toLocaleUpperCase"], + string +> = uncurryThis(StringPrototype.toLocaleUpperCase); +export var StringPrototypeToLocaleString: Uncurry< + String["toLocaleString"], + string +> = uncurryThis(StringPrototype.toLocaleString); +export var StringPrototypeToString: Uncurry = + uncurryThis(StringPrototype.toString); +export var StringPrototypeToWellFormed: Uncurry< + String["toWellFormed"], + string +> = uncurryThis(StringPrototype.toWellFormed); +export var StringPrototypeTrim: Uncurry = uncurryThis( + StringPrototype.trim, +); +export var StringPrototypeTrimStart: Uncurry = + uncurryThis(StringPrototype.trimStart); +export var StringPrototypeTrimEnd: Uncurry = + uncurryThis(StringPrototype.trimEnd); +export var StringPrototypeValueOf: Uncurry = + uncurryThis(StringPrototype.valueOf); +export var StringPrototypeGetLength: (string: string) => number = uncurryGetter( + StringPrototype, + "length", + "wrap", +); +export var StringPrototypeSymbolIterator: Uncurry< + String[SymbolIterator], + string +> = uncurryThis(StringPrototype[SymbolIterator]); + +export var StringIteratorPrototype: StringIterator = + ObjectGetPrototypeOf( + StringPrototypeSymbolIterator(""), + ); +export var StringIteratorPrototypeNext: Uncurry< + StringIterator["next"], + StringIterator +> = uncurryThis(StringIteratorPrototype.next); +export var StringIteratorPrototypeReturn: Uncurry< + StringIterator["return"], + StringIterator +> = uncurryThis(StringIteratorPrototype.return ?? (() => undefined!)); +export var StringIteratorPrototypeThrow: Uncurry< + StringIterator["throw"], + StringIterator +> = uncurryThis( + StringIteratorPrototype.throw ?? ((e) => { + throw Error.isError(e) ? e : new Error(e); + }), +); +// #endregion String + +// #region Number +export var Number: NumberConstructor = $globalThis.Number; +export var NumberNaN: typeof Number.NaN = Number.NaN; +export var NumberIsNaN: typeof Number.isNaN = Number.isNaN; +export var NumberIsFinite: typeof Number.isFinite = Number.isFinite; +export var NumberIsInteger: typeof Number.isInteger = Number.isInteger; +export var NumberIsSafeInteger: typeof Number.isSafeInteger = + Number.isSafeInteger; +export var NumberParseFloat: typeof Number.parseFloat = Number.parseFloat; +export var NumberParseInt: typeof Number.parseInt = Number.parseInt; +export var NumberEPSILON: typeof Number.EPSILON = Number.EPSILON; +export var NumberMAX_SAFE_INTEGER: typeof Number.MAX_SAFE_INTEGER = + Number.MAX_SAFE_INTEGER; +export var NumberMIN_SAFE_INTEGER: typeof Number.MIN_SAFE_INTEGER = + Number.MIN_SAFE_INTEGER; +export var NumberMAX_VALUE: typeof Number.MAX_VALUE = Number.MAX_VALUE; +export var NumberMIN_VALUE: typeof Number.MIN_VALUE = Number.MIN_VALUE; +export var NumberPOSITIVE_INFINITY: typeof Number.POSITIVE_INFINITY = + Number.POSITIVE_INFINITY; +export var NumberNEGATIVE_INFINITY: typeof Number.NEGATIVE_INFINITY = + Number.NEGATIVE_INFINITY; +export var NumberPrototype: Number = Number.prototype; +export var NumberPrototypeToString: Uncurry = + uncurryThis( + NumberPrototype.toString, + ); +export var NumberPrototypeToFixed: Uncurry = + uncurryThis( + NumberPrototype.toFixed, + ); +export var NumberPrototypeToExponential: Uncurry< + Number["toExponential"], + number +> = uncurryThis( + NumberPrototype.toExponential, +); +export var NumberPrototypeToPrecision: Uncurry = + uncurryThis( + NumberPrototype.toPrecision, + ); +// #endregion Number + +// #region BigInt +export var BigInt: BigIntConstructor = $globalThis.BigInt; +export var BigIntPrototype: BigInt = BigInt.prototype; +export var BigIntPrototypeToString: Uncurry = + uncurryThis( + BigIntPrototype.toString, + ); +export var BigIntPrototypeValueOf: Uncurry = + uncurryThis( + BigIntPrototype.valueOf, + ); +export var BigIntAsIntN: typeof BigInt.asIntN = BigInt.asIntN; +export var BigIntAsUintN: typeof BigInt.asUintN = BigInt.asUintN; +// #endregion BigInt + +// #region Boolean +export var Boolean: BooleanConstructor = $globalThis.Boolean; +export var BooleanPrototype: Boolean = Boolean.prototype; +export var BooleanPrototypeToString: Uncurry = + uncurryThis( + BooleanPrototype.toString, + ); +export var BooleanPrototypeValueOf: Uncurry = + uncurryThis( + BooleanPrototype.valueOf, + ); +// #endregion Boolean + +// #region Atomics +export var Atomics: globalThis.Atomics = $globalThis.Atomics; +export var AtomicsAdd: typeof Atomics.add = Atomics.add; +export var AtomicsAnd: typeof Atomics.and = Atomics.and; +// deno-fmt-ignore +export var AtomicsCompareExchange: typeof Atomics.compareExchange = Atomics.compareExchange; +export var AtomicsExchange: typeof Atomics.exchange = Atomics.exchange; +export var AtomicsIsLockFree: typeof Atomics.isLockFree = Atomics.isLockFree; +export var AtomicsLoad: typeof Atomics.load = Atomics.load; +export var AtomicsNotify: typeof Atomics.notify = Atomics.notify; +export var AtomicsOr: typeof Atomics.or = Atomics.or; +export var AtomicsPause: typeof Atomics.pause = Atomics.pause; +export var AtomicsStore: typeof Atomics.store = Atomics.store; +export var AtomicsSub: typeof Atomics.sub = Atomics.sub; +export var AtomicsWait: typeof Atomics.wait = Atomics.wait; +export var AtomicsWaitAsync: typeof Atomics.waitAsync = Atomics.waitAsync; +export var AtomicsXor: typeof Atomics.xor = Atomics.xor; +// #endregion Atomics + +// #region Proxy and Reflection +export var Proxy: ProxyConstructor = $globalThis.Proxy; +export type Proxy = T & { [K in keyof T]: T[K] }; +export var ProxyRevocable: typeof Proxy.revocable = Proxy.revocable; +export type ProxyHandler = globalThis.ProxyHandler; + +export var Reflect: typeof $globalThis.Reflect = $globalThis.Reflect; +export var ReflectApply: typeof Reflect.apply = Reflect.apply; +export var ReflectConstruct: typeof Reflect.construct = Reflect.construct; +export var ReflectDefineProperty: typeof Reflect.defineProperty = + Reflect.defineProperty; +export var ReflectDeleteProperty: typeof Reflect.deleteProperty = + Reflect.deleteProperty; +export var ReflectGet: typeof Reflect.get = Reflect.get; +export var ReflectGetOwnPropertyDescriptor: + typeof Reflect.getOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor; +export var ReflectGetPrototypeOf: typeof Reflect.getPrototypeOf = + Reflect.getPrototypeOf; +export var ReflectHas: typeof Reflect.has = Reflect.has; +export var ReflectIsExtensible: typeof Reflect.isExtensible = + Reflect.isExtensible; +export var ReflectOwnKeys: typeof Reflect.ownKeys = Reflect.ownKeys; +export var ReflectPreventExtensions: typeof Reflect.preventExtensions = + Reflect.preventExtensions; +export var ReflectSet: typeof Reflect.set = Reflect.set; +export var ReflectSetPrototypeOf: typeof Reflect.setPrototypeOf = + Reflect.setPrototypeOf; +// #endregion Proxy and Reflection + +// #region Keyed Collections +export var Set: SetConstructor = $globalThis.Set; +export var SetPrototype: Set = Set?.prototype; +export var SetPrototypeHas: Uncurry["has"], Set> = uncurryThis( + SetPrototype?.has ?? + (() => fail("Set is not supported in this environment.")), + SetPrototype, +); + +export var Map: MapConstructor = $globalThis.Map; +export var MapGroupBy: typeof Map.groupBy = Map.groupBy; +export var MapPrototype: Map = Map?.prototype; +export var MapPrototypeHas: Uncurry["has"], Map> = + uncurryThis( + MapPrototype?.has ?? + (() => fail("Map is not supported in this environment.")), + MapPrototype, + ); +// #endregion Keyed Collections + +// #region Weak Keyed Collections +interface WeakKeyTypes { + object: object; +} +interface WeakKeyTypes { + symbol: symbol; +} + +export type WeakKey = WeakKeyTypes[keyof WeakKeyTypes]; + +export var WeakMap: WeakMapConstructor = $globalThis.WeakMap; +export var WeakMapPrototype: WeakMap = WeakMap?.prototype; +export var WeakMapPrototypeHas: Uncurry< + WeakMap["has"], + WeakMap +> = uncurryThis( + WeakMapPrototype?.has ?? + (() => fail("WeakMap is not supported in this environment.")), +); + +export var WeakSet: WeakSetConstructor = $globalThis.WeakSet; +export var WeakSetPrototype: WeakSet = WeakSet?.prototype; +export var WeakSetPrototypeHas: Uncurry< + WeakSet["has"], + WeakSet +> = uncurryThis( + WeakSetPrototype?.has ?? + (() => fail("WeakSet is not supported in this environment.")), +); + +export var WeakRef: WeakRefConstructor = $globalThis.WeakRef; +export var WeakRefPrototype: WeakRef = WeakRef?.prototype; +export var WeakRefPrototypeDeref: Uncurry< + WeakRef["deref"], + WeakRef +> = uncurryThis( + WeakRefPrototype?.deref ?? + (() => fail("WeakRef is not supported in this environment.")), +); + +export var FinalizationRegistry: FinalizationRegistryConstructor = + $globalThis.FinalizationRegistry; +export var FinalizationRegistryPrototype: FinalizationRegistry = + FinalizationRegistry?.prototype; +export var FinalizationRegistryPrototypeRegister: ( + registry: FinalizationRegistry, + target: WeakKey, + heldValue: T, + unregisterToken?: WeakKey, +) => void = uncurryThis( + FinalizationRegistryPrototype?.register ?? + (() => fail("FinalizationRegistry is not supported in this environment.")), +); +export var FinalizationRegistryPrototypeUnregister: ( + registry: FinalizationRegistry, + unregisterToken: WeakKey, +) => boolean = uncurryThis( + FinalizationRegistryPrototype?.unregister ?? + (() => fail("FinalizationRegistry is not supported in this environment.")), +); + +export var FinalizationRegistryPrototypeCleanupSome: ( + registry: FinalizationRegistry, +) => boolean = uncurryThis( + (FinalizationRegistryPrototype as any)?.cleanupSome ?? + (() => fail("FinalizationRegistry is not supported in this environment.")), +); +// #endregion Weak Keyed Collections + +// #region Errors +export var Error: ErrorConstructor = $globalThis.Error; +export var ErrorCaptureStackTrace: typeof Error.captureStackTrace = + Error.captureStackTrace; +export var TypeError: TypeErrorConstructor = $globalThis.TypeError; +export var ReferenceError: ReferenceErrorConstructor = + $globalThis.ReferenceError; +export var SyntaxError: SyntaxErrorConstructor = $globalThis.SyntaxError; +export var RangeError: RangeErrorConstructor = $globalThis.RangeError; +export var EvalError: EvalErrorConstructor = $globalThis.EvalError; +export var URIError: URIErrorConstructor = $globalThis.URIError; +// #endregion Errors + +// #region Structured Data +export var ArrayBuffer: ArrayBufferConstructor = $globalThis.ArrayBuffer; +// deno-fmt-ignore +export var SharedArrayBuffer: SharedArrayBufferConstructor = $globalThis.SharedArrayBuffer; +export var DataView: typeof $globalThis.DataView = $globalThis.DataView; +export type DataView = + globalThis.DataView; + +export var Int8Array: typeof $globalThis.Int8Array = $globalThis.Int8Array; +export type Int8Array = + globalThis.Int8Array; + +export var Int16Array: typeof $globalThis.Int16Array = $globalThis.Int16Array; +export type Int16Array = + globalThis.Int16Array; + +export var Int32Array: typeof $globalThis.Int32Array = $globalThis.Int32Array; +export type Int32Array = + globalThis.Int32Array; + +export var Uint8Array: typeof $globalThis.Uint8Array = $globalThis.Uint8Array; +export type Uint8Array = + globalThis.Uint8Array; + +// deno-fmt-ignore +export var Uint8ClampedArray: typeof $globalThis.Uint8ClampedArray = $globalThis.Uint8ClampedArray; +export type Uint8ClampedArray = + globalThis.Uint8ClampedArray; + +export var Uint16Array: typeof $globalThis.Uint16Array = + $globalThis.Uint16Array; +export type Uint16Array = + globalThis.Uint16Array; + +export var Uint32Array: typeof $globalThis.Uint32Array = + $globalThis.Uint32Array; +export type Uint32Array = + globalThis.Uint32Array; + +export var Float16Array: typeof $globalThis.Float16Array = + $globalThis.Float16Array; +export type Float16Array = + globalThis.Float16Array; + +export var Float32Array: typeof $globalThis.Float32Array = + $globalThis.Float32Array; +export type Float32Array = + globalThis.Float32Array; + +export var Float64Array: typeof $globalThis.Float64Array = + $globalThis.Float64Array; +export type Float64Array = + globalThis.Float64Array; + +export var BigInt64Array: typeof $globalThis.BigInt64Array = + $globalThis.BigInt64Array; +export type BigInt64Array = + globalThis.BigInt64Array; + +// deno-fmt-ignore +export var BigUint64Array: typeof $globalThis.BigUint64Array = $globalThis.BigUint64Array; +export type BigUint64Array = + globalThis.BigUint64Array; +// #endregion Structured Data + +// #region Event +export type ElementConstructor = typeof $globalThis extends { Element: infer E } + ? E + : { new (): never; prototype: Element }; +export type Element = typeof $globalThis extends + { Element: infer E extends abstract new (...args: any) => any } + ? InstanceType + : any; + +export type EventConstructor = typeof $globalThis extends { Event: infer E } ? E + : { new (type: string, init?: EventInit): Event; prototype: Event }; +export var Event: EventConstructor = $globalThis.Event; +export type Event = globalThis.Event; +export var EventPrototype: Event = Event.prototype; +export var EventPrototypeStopPropagation: Uncurry< + Event["stopPropagation"], + Event +> = uncurryThis( + EventPrototype.stopPropagation, +); +export var EventPrototypePreventDefault: Uncurry< + Event["preventDefault"], + Event +> = uncurryThis( + EventPrototype.preventDefault, +); +export var EventPrototypeStopImmediatePropagation: Uncurry< + Event["stopImmediatePropagation"], + Event +> = uncurryThis( + EventPrototype.stopImmediatePropagation, +); +export var EventPrototypeGetType: (event: Event) => string = uncurryGetter( + EventPrototype, + "type", + "stub", +); +export var EventPrototypeGetTarget: (event: Event) => EventTarget | null = + uncurryGetter( + EventPrototype, + "target", + "stub", + ); +export var EventPrototypeGetCurrentTarget: ( + event: Event, +) => EventTarget | null = uncurryGetter( + EventPrototype, + "currentTarget", + "stub", +); +export var EventPrototypeGetBubbles: (event: Event) => boolean = uncurryGetter( + EventPrototype, + "bubbles", + "stub", +); +export var EventPrototypeGetCancelable: (event: Event) => boolean = + uncurryGetter( + EventPrototype, + "cancelable", + "stub", + ); +export var EventPrototypeGetDefaultPrevented: (event: Event) => boolean = + uncurryGetter( + EventPrototype, + "defaultPrevented", + "stub", + ); +export var EventPrototypeGetComposed: (event: Event) => boolean = uncurryGetter( + EventPrototype, + "composed", + "stub", +); +export var EventPrototypeGetTimeStamp: (event: Event) => number = uncurryGetter( + EventPrototype, + "timeStamp", + "stub", +); +export var EventPrototypeGetEventPhase: (event: Event) => number = + uncurryGetter( + EventPrototype, + "eventPhase", + "stub", + ); +export var EventPrototypeGetIsTrusted: (event: Event) => boolean = + uncurryGetter( + EventPrototype, + "isTrusted", + "stub", + ); +export var EventPrototypeGetInitialized: (event: Event) => boolean = + uncurryGetter( + EventPrototype, + "initialized", + "stub", + ); +export var EventPrototypeComposedPath: (event: Event) => EventTarget[] = + uncurryThis( + EventPrototype.composedPath, + ); +export var EventPrototypeGetNONE: (event: Event) => 0 = uncurryGetter( + EventPrototype, + "NONE", + "stub", +); +export var EventPrototypeGetCAPTURING_PHASE: (event: Event) => 1 = + uncurryGetter( + EventPrototype, + "CAPTURING_PHASE", + "stub", + ); +export var EventPrototypeGetAT_TARGET: (event: Event) => 2 = uncurryGetter( + EventPrototype, + "AT_TARGET", + "stub", +); +export var EventPrototypeGetBUBBLING_PHASE: (event: Event) => 3 = uncurryGetter( + EventPrototype, + "BUBBLING_PHASE", + "stub", +); +export var EventPrototypeGetReturnValue: (event: Event) => any = uncurryGetter( + EventPrototype, + "returnValue", + "stub", +); +export var EventPrototypeSetReturnValue: (event: Event, value: any) => void = + uncurrySetter( + EventPrototype, + "returnValue", + "stub", + ); +export var EventPrototypeGetCancelBubble: (event: Event) => boolean = + uncurryGetter( + EventPrototype, + "cancelBubble", + "stub", + ); +export var EventPrototypeSetCancelBubble: ( + event: Event, + cancelBubble: boolean, +) => void = uncurrySetter( + EventPrototype, + "cancelBubble", + "stub", +); +// #endregion Event + +// #region EventTarget +export type EventTargetConstructor = typeof $globalThis extends + { EventTarget: infer E } ? E + : { new (): EventTarget; readonly prototype: EventTarget }; +export var EventTarget: EventTargetConstructor = $globalThis.EventTarget; +export type EventTarget = globalThis.EventTarget; + +export var EventTargetPrototype: EventTarget = EventTarget.prototype; +export var EventTargetPrototypeAddEventListener: Uncurry< + EventTarget["addEventListener"], + EventTarget +> = uncurryThis(EventTargetPrototype.addEventListener); +export var EventTargetPrototypeRemoveEventListener: Uncurry< + EventTarget["removeEventListener"], + EventTarget +> = uncurryThis(EventTargetPrototype.removeEventListener); +export var EventTargetPrototypeDispatchEvent: Uncurry< + EventTarget["dispatchEvent"], + EventTarget +> = uncurryThis(EventTargetPrototype.dispatchEvent); +// #endregion Event diff --git a/src/_internal/to_string.ts b/src/internal/to_string.ts similarity index 60% rename from src/_internal/to_string.ts rename to src/internal/to_string.ts index 6f80b44..76a5a46 100644 --- a/src/_internal/to_string.ts +++ b/src/internal/to_string.ts @@ -1,15 +1,14 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/to-string + * @see https://jsr.io/@nick/is/doc/internal/to-string */ - -import { uncurryThis } from "./uncurry_this.ts"; -import { Object } from "./primordials.ts"; +import { ObjectPrototypeToString } from "./primordials.ts"; /** * An uncurried version of the `Object.prototype.toString` method, which allows * for the `this` binding to be passed as the first argument. + * * @example * ```ts * import { toString } from "./src/_internal.ts"; @@ -18,6 +17,7 @@ import { Object } from "./primordials.ts"; * console.log(toString([])); // "[object Array]" * ``` */ -export const toString = uncurryThis(Object.prototype.toString) as - & ((target: T) => `[object ${string}]`) - & ((target: unknown) => string); +export const toString: { + (target: T): `[object ${string}]`; + (target: unknown): string; +} = ObjectPrototypeToString as never; diff --git a/src/internal/try_getter.ts b/src/internal/try_getter.ts new file mode 100644 index 0000000..f5ba75f --- /dev/null +++ b/src/internal/try_getter.ts @@ -0,0 +1,50 @@ +import { + FunctionPrototypeCall, + ObjectGetOwnPropertyDescriptor, + ObjectHasOwn, +} from "./primordials.ts"; + +/** + * Attempts to call {@link key} on the provided {@link prototype}, using + * {@link thisArg} for its contextual `this` binding. If no error is thrown, + * returns `true`. Otherwise, this returns `false`. + * + * **Note**: the `prototype` object **must** have the property `key` defined + * as an own **getter** method. This is due to the fact this guard relies on + * `Object.getOwnPropertyDescriptor` - it specifically expects the returned + * descriptor to be a non-null object, and for it to have a `get` method. If + * either of these conditions are not met, this method will return `false`. + * + * @template {{ [P in K]: V } & { [x: PropertyKey]: any }} T The prototype + * object to check the getter method on. + * @template {PropertyKey} [K=keyof T] The key for the getter method. + * @template [V=T[K]] The value type for the getter method. + * @param prototype The object to check the getter method on. + * @param key The key for the getter method. + * @param thisArg The contextual `this` binding for the getter method. This is + * the parameter that has its type narrowed by this type guard. For example, to + * check if a given object is an `ArrayBuffer` instance, you could call this + * method with the arguments `ArrayBuffer.prototype`, `"byteLength"`, and then + * the unknown value you wish to check for its `thisArg` parameter. If the test + * passes, the `thisArg` value's type will be narrowed to `ArrayBuffer`. + * @returns `true` if the getter was successfully called; otherwise, `false`. + * @internal + */ +export function tryGetter< + // deno-lint-ignore no-explicit-any + T extends { [P in K]: V } & { [x: PropertyKey]: any }, + K extends PropertyKey = keyof T, + V = T[K], +>(prototype: T | { [P in K]: V }, key: K, thisArg: unknown): thisArg is T { + try { + if (key in prototype && ObjectHasOwn(prototype, key)) { + const descriptor = ObjectGetOwnPropertyDescriptor(prototype, key); + if (typeof descriptor?.get === "function") { + FunctionPrototypeCall(descriptor.get, thisArg); + return true; + } + } + } catch { /* ignore */ } + + return false; +} diff --git a/src/_internal/try_method.ts b/src/internal/try_method.ts similarity index 93% rename from src/_internal/try_method.ts rename to src/internal/try_method.ts index c2e1802..f8a2bab 100644 --- a/src/_internal/try_method.ts +++ b/src/internal/try_method.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/try-method + * @see https://jsr.io/@nick/is/doc/internal/try-method */ import { FunctionPrototypeCall } from "./primordials.ts"; diff --git a/src/_internal/try_value_of.ts b/src/internal/try_value_of.ts similarity index 90% rename from src/_internal/try_value_of.ts rename to src/internal/try_value_of.ts index cbcc94c..a5b4f66 100644 --- a/src/_internal/try_value_of.ts +++ b/src/internal/try_value_of.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/try-value-of + * @see https://jsr.io/@nick/is/doc/internal/try-value-of */ import { tryMethod } from "./try_method.ts"; diff --git a/src/_internal/types.ts b/src/internal/types.ts similarity index 81% rename from src/_internal/types.ts rename to src/internal/types.ts index 19be900..2297a5e 100644 --- a/src/_internal/types.ts +++ b/src/internal/types.ts @@ -1,8 +1,8 @@ -// deno-lint-ignore-file ban-types +// deno-lint-ignore-file ban-types no-explicit-any /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/types + * @see https://jsr.io/@nick/is/doc/internal/types */ const BRAND: unique symbol = Symbol("BRAND"); @@ -45,11 +45,24 @@ export type unknowns = {} | null | undefined; export type Expand = T extends infer T ? T : Fallback; -export type ObjectEntry = { [K in keyof T]: [K, T[K]] }[keyof T]; -export type ObjectEntries = ObjectEntry[]; export type ObjectKeys = (string & keyof T)[]; + export type ObjectValues = T[keyof T][]; +export type ObjectEntry = { [K in keyof T]: [K, T[K]] }[keyof T]; + +export type ObjectEntries = ObjectEntry[]; + +export type ObjectFromEntries< + T extends readonly (readonly [PropertyKey, any])[], +> = { + [ + K in keyof T as K extends number | `${number}` + ? T[K] extends [PropertyKey, any] ? T[K][0] : never + : never + ]: T[K] extends [PropertyKey, any] ? T[K][1] : never; +}; + export type Split< S extends string, C extends string = "", diff --git a/src/internal/uncurry_getter.ts b/src/internal/uncurry_getter.ts new file mode 100644 index 0000000..e0b9797 --- /dev/null +++ b/src/internal/uncurry_getter.ts @@ -0,0 +1,101 @@ +/*! + * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. + * @license MIT (https://nick.mit-license.org/2024) + * @see https://jsr.io/@nick/is/doc/internal/uncurry-getter + */ + +import { fail } from "./fail.ts"; +import { + bind, + call, + FunctionPrototypeCall, + ObjectGetOwnPropertyDescriptor, + String, + TypeError, +} from "./primordials.ts"; + +/** @internal */ +export function uncurryGetter< + T extends object, + K extends NonNullable | keyof T, +>( + target: T, + key: K, + assert: true | "stub" | "wrap", + message?: string, +): K extends keyof T ? (self: T) => T[K] : never; +/** @internal */ +export function uncurryGetter< + T extends object, + K extends NonNullable | keyof T, +>( + target: T, + key: K, + assert?: boolean, + message?: string, +): ((self: T) => T[K & keyof T]) | undefined; +/** @internal */ +export function uncurryGetter( + target: object, + key: PropertyKey, + assert?: boolean | "stub" | "wrap", + message?: string, +): ((self: object) => unknown) | undefined { + if ( + typeof target !== "function" && + (typeof target !== "object" || target === null) + ) { + if (assert === "stub" || assert === "wrap") { + return () => { + fail(message ?? "Target must be an object.", uncurryGetter); + }; + } else if (assert) { + fail("Target must be an object.", uncurryGetter); + } + } else { + const desc = ObjectGetOwnPropertyDescriptor(target, key); + // if (desc?.get) return bind.call(call, desc.get); + if (typeof desc?.get === "function") { + return FunctionPrototypeCall( + bind, + call, + desc.get, + ); + } else if (assert === "wrap") { + return (self) => { + let cause: unknown; + try { + // deno-lint-ignore no-explicit-any + return desc?.value ?? (self as any)[key]; + } catch (e) { + cause = e; + } + fail( + new TypeError( + message ?? + `Property '${ + String(key) + }' does not exist or is not a getter/field on the target object.`, + { cause }, + ), + uncurryGetter, + ); + }; + } else if (assert === "stub") { + return () => { + fail( + message ?? + `Property '${ + String(key) + }' does not exist or is not a getter/field on the target object.`, + uncurryGetter, + ); + }; + } else if (assert) { + fail( + message || `Property '${String(key)}' is not a getter.`, + uncurryGetter, + ); + } + } +} diff --git a/src/_internal/uncurry_getter.ts b/src/internal/uncurry_setter.ts similarity index 70% rename from src/_internal/uncurry_getter.ts rename to src/internal/uncurry_setter.ts index e5a214b..9463168 100644 --- a/src/_internal/uncurry_getter.ts +++ b/src/internal/uncurry_setter.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/uncurry-getter + * @see https://jsr.io/@nick/is/doc/internal/uncurry-setter */ import { @@ -15,7 +15,7 @@ import { } from "./primordials.ts"; /** @internal */ -export function uncurryGetter< +export function uncurrySetter< T extends object, K extends NonNullable | keyof T, >( @@ -23,9 +23,9 @@ export function uncurryGetter< key: K, assert: true | "stub", message?: string, -): K extends keyof T ? (self: T) => T[K] : never; +): K extends keyof T ? (self: T, value: T[K]) => void : never; /** @internal */ -export function uncurryGetter< +export function uncurrySetter< T extends object, K extends NonNullable | keyof T, >( @@ -33,14 +33,14 @@ export function uncurryGetter< key: K, assert?: boolean, message?: string, -): ((self: T) => T[K & keyof T]) | undefined; +): ((self: T, value: T[K & keyof T]) => void) | undefined; /** @internal */ -export function uncurryGetter( +export function uncurrySetter( target: object, key: PropertyKey, assert?: boolean | "stub", message?: string, -): ((self: object) => unknown) | undefined { +): ((self: object, value: unknown) => void) | undefined { if (typeof target !== "object" || target === null) { if (assert === "stub") { return () => { @@ -51,20 +51,20 @@ export function uncurryGetter( } } else { const desc = ObjectGetOwnPropertyDescriptor(target, key); - // if (desc?.get) return bind.call(call, desc.get); - if (desc?.get) { + // if (desc?.set) return bind.call(call, desc.set); + if (desc?.set) { return FunctionPrototypeCall( bind, call, - desc.get, + desc.set, ); } if (assert) { if (!message) { - message = `Property '${String(key)}' is not a getter.`; + message = `Property '${String(key)}' is not a setter.`; } const error = new TypeError(message); - ErrorCaptureStackTrace?.(error, uncurryGetter); + ErrorCaptureStackTrace?.(error, uncurrySetter); error.stack; // trigger lazy stack capture throw error; } diff --git a/src/_internal/uncurry_this.ts b/src/internal/uncurry_this.ts similarity index 81% rename from src/_internal/uncurry_this.ts rename to src/internal/uncurry_this.ts index 61590bb..9de8ba0 100644 --- a/src/_internal/uncurry_this.ts +++ b/src/internal/uncurry_this.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/uncurry-this + * @see https://jsr.io/@nick/is/doc/internal/uncurry-this */ import { FunctionPrototype, uncurryThis } from "./primordials.ts"; diff --git a/src/_internal/unicode_regexp.ts b/src/internal/unicode_regexp.ts similarity index 99% rename from src/_internal/unicode_regexp.ts rename to src/internal/unicode_regexp.ts index 5178e9e..6d5679e 100644 --- a/src/_internal/unicode_regexp.ts +++ b/src/internal/unicode_regexp.ts @@ -1,7 +1,7 @@ /*! * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/unicode-regexp + * @see https://jsr.io/@nick/is/doc/internal/unicode-regexp */ // surrogate-safe patterns adapted from https://github.com/mathiasbynens/unicode-8.0.0 From 325d4970e1ec8acd6a2a7f99083f303f8659acf2 Mon Sep 17 00:00:00 2001 From: Nicholas Berlette Date: Fri, 25 Jul 2025 00:29:23 +0000 Subject: [PATCH 10/24] chore: remove copyright header from test files --- src/number/finite_integer.test.ts | 6 ------ src/number/float16.test.ts | 6 ------ src/number/float32.test.ts | 6 ------ src/number/in_range.test.ts | 5 ----- src/number/int16.test.ts | 6 ------ src/number/int32.test.ts | 6 ------ src/number/int8.test.ts | 6 ------ src/number/integer.test.ts | 6 ------ src/number/nan.test.ts | 6 ------ src/number/negative_nonzero.test.ts | 6 ------ src/number/negative_nonzero_finite.test.ts | 6 ------ src/number/negative_zero.test.ts | 6 ------ src/number/nonzero_finite_integer.test.ts | 6 ------ src/number/nonzero_integer.test.ts | 6 ------ src/number/odd.test.ts | 6 ------ src/number/positive_finite.test.ts | 6 ------ src/number/positive_finite_integer.test.ts | 6 ------ src/number/positive_integer.test.ts | 5 ----- src/number/positive_nonzero.test.ts | 6 ------ src/number/positive_nonzero_finite.test.ts | 6 ------ src/number/positive_nonzero_finite_integer.test.ts | 6 ------ src/number/positive_nonzero_integer.test.ts | 6 ------ src/number/positive_zero.test.ts | 6 ------ 23 files changed, 136 deletions(-) diff --git a/src/number/finite_integer.test.ts b/src/number/finite_integer.test.ts index a8edf36..438c7fc 100644 --- a/src/number/finite_integer.test.ts +++ b/src/number/finite_integer.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/finite-integer - */ - import { assertEquals } from "@std/assert"; import { isFiniteInteger } from "./finite_integer.ts"; diff --git a/src/number/float16.test.ts b/src/number/float16.test.ts index 03c57c8..5e8f385 100644 --- a/src/number/float16.test.ts +++ b/src/number/float16.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/float16 - */ - import { assertEquals } from "@std/assert"; import { isFloat16 } from "./float16.ts"; diff --git a/src/number/float32.test.ts b/src/number/float32.test.ts index 357f94c..68172d2 100644 --- a/src/number/float32.test.ts +++ b/src/number/float32.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/float32 - */ - import { assertEquals } from "@std/assert"; import { isFloat32 } from "./float32.ts"; diff --git a/src/number/in_range.test.ts b/src/number/in_range.test.ts index 14e91c8..e69de29 100644 --- a/src/number/in_range.test.ts +++ b/src/number/in_range.test.ts @@ -1,5 +0,0 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/in-range - */ diff --git a/src/number/int16.test.ts b/src/number/int16.test.ts index 3d3e181..2c38574 100644 --- a/src/number/int16.test.ts +++ b/src/number/int16.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/int16 - */ - import { assertEquals } from "@std/assert"; import { isInt16 } from "./int16.ts"; diff --git a/src/number/int32.test.ts b/src/number/int32.test.ts index 712beb2..7e75e8b 100644 --- a/src/number/int32.test.ts +++ b/src/number/int32.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/int32 - */ - import { assertEquals } from "@std/assert"; import { isInt32 } from "./int32.ts"; diff --git a/src/number/int8.test.ts b/src/number/int8.test.ts index 957f775..a10075a 100644 --- a/src/number/int8.test.ts +++ b/src/number/int8.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/int8 - */ - import { assertEquals } from "@std/assert"; import { isInt8 } from "./int8.ts"; diff --git a/src/number/integer.test.ts b/src/number/integer.test.ts index 86dbaa8..0ad0997 100644 --- a/src/number/integer.test.ts +++ b/src/number/integer.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/integer - */ - import { assert, assertEquals } from "@std/assert"; import { isInteger } from "./integer.ts"; diff --git a/src/number/nan.test.ts b/src/number/nan.test.ts index d478445..5b0e36d 100644 --- a/src/number/nan.test.ts +++ b/src/number/nan.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/nan - */ - import { assertEquals } from "@std/assert"; import { isNaN, type NaN } from "./nan.ts"; diff --git a/src/number/negative_nonzero.test.ts b/src/number/negative_nonzero.test.ts index 2400a08..7e88e04 100644 --- a/src/number/negative_nonzero.test.ts +++ b/src/number/negative_nonzero.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/negative-nonzero - */ - import { assertEquals } from "@std/assert"; import { isNegativeNonZeroNumber } from "./negative_nonzero.ts"; diff --git a/src/number/negative_nonzero_finite.test.ts b/src/number/negative_nonzero_finite.test.ts index a450ae2..2039fa6 100644 --- a/src/number/negative_nonzero_finite.test.ts +++ b/src/number/negative_nonzero_finite.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/negative-nonzero-finite - */ - import { assertEquals } from "@std/assert"; import { isNegativeNonZeroFiniteNumber } from "./negative_nonzero_finite.ts"; diff --git a/src/number/negative_zero.test.ts b/src/number/negative_zero.test.ts index e8e6abe..392ec34 100644 --- a/src/number/negative_zero.test.ts +++ b/src/number/negative_zero.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/negative-zero - */ - import { assertEquals } from "@std/assert"; import { isNegativeZero } from "./negative_zero.ts"; diff --git a/src/number/nonzero_finite_integer.test.ts b/src/number/nonzero_finite_integer.test.ts index 208fc61..ecda0f7 100644 --- a/src/number/nonzero_finite_integer.test.ts +++ b/src/number/nonzero_finite_integer.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/nonzero-finite-integer - */ - import { assertEquals } from "@std/assert"; import { isNonZeroFiniteInteger } from "./nonzero_finite_integer.ts"; diff --git a/src/number/nonzero_integer.test.ts b/src/number/nonzero_integer.test.ts index 1a20410..9638fa1 100644 --- a/src/number/nonzero_integer.test.ts +++ b/src/number/nonzero_integer.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/nonzero-integer - */ - import { assertEquals } from "@std/assert"; import { isNonZeroInteger } from "./nonzero_integer.ts"; diff --git a/src/number/odd.test.ts b/src/number/odd.test.ts index 644c825..8ca367f 100644 --- a/src/number/odd.test.ts +++ b/src/number/odd.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/odd - */ - import { assertEquals } from "@std/assert"; import { isOdd } from "./odd.ts"; diff --git a/src/number/positive_finite.test.ts b/src/number/positive_finite.test.ts index cfa416f..c14ee56 100644 --- a/src/number/positive_finite.test.ts +++ b/src/number/positive_finite.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/positive-finite - */ - import { assertEquals } from "@std/assert"; import { isPositiveFiniteNumber } from "./positive_finite.ts"; diff --git a/src/number/positive_finite_integer.test.ts b/src/number/positive_finite_integer.test.ts index 8539b15..1a42986 100644 --- a/src/number/positive_finite_integer.test.ts +++ b/src/number/positive_finite_integer.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/positive-finite-integer - */ - import { assertEquals } from "@std/assert"; import { isPositiveFiniteInteger } from "./positive_finite_integer.ts"; diff --git a/src/number/positive_integer.test.ts b/src/number/positive_integer.test.ts index b9deecc..76c5f39 100644 --- a/src/number/positive_integer.test.ts +++ b/src/number/positive_integer.test.ts @@ -1,8 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/positive-integer - */ import { describe, it } from "@std/testing/bdd"; import { expect } from "@std/expect"; import { isPositiveInteger } from "./positive_integer.ts"; diff --git a/src/number/positive_nonzero.test.ts b/src/number/positive_nonzero.test.ts index 3abedac..8b0ea24 100644 --- a/src/number/positive_nonzero.test.ts +++ b/src/number/positive_nonzero.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/positive-nonzero - */ - import { assertEquals } from "@std/assert"; import { isPositiveNonZeroNumber, diff --git a/src/number/positive_nonzero_finite.test.ts b/src/number/positive_nonzero_finite.test.ts index cd3522c..a114789 100644 --- a/src/number/positive_nonzero_finite.test.ts +++ b/src/number/positive_nonzero_finite.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/positive-nonzero-finite - */ - import { assertEquals } from "@std/assert"; import { isPositiveNonZeroFiniteNumber } from "./positive_nonzero_finite.ts"; diff --git a/src/number/positive_nonzero_finite_integer.test.ts b/src/number/positive_nonzero_finite_integer.test.ts index 3cec840..20fc90d 100644 --- a/src/number/positive_nonzero_finite_integer.test.ts +++ b/src/number/positive_nonzero_finite_integer.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/positive-nonzero-finite-integer - */ - import { assertEquals } from "@std/assert"; import { isPositiveNonZeroFiniteInteger } from "./positive_nonzero_finite_integer.ts"; diff --git a/src/number/positive_nonzero_integer.test.ts b/src/number/positive_nonzero_integer.test.ts index 50daa1c..80a9ca0 100644 --- a/src/number/positive_nonzero_integer.test.ts +++ b/src/number/positive_nonzero_integer.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/positive-nonzero-integer - */ - import { assertEquals } from "@std/assert"; import { isPositiveNonZeroInteger } from "./positive_nonzero_integer.ts"; diff --git a/src/number/positive_zero.test.ts b/src/number/positive_zero.test.ts index c545a05..3343c39 100644 --- a/src/number/positive_zero.test.ts +++ b/src/number/positive_zero.test.ts @@ -1,9 +1,3 @@ -/*! - * Copyright (c) 2024-2025 Nicholas Berlette. All rights reserved. - * @license MIT (https://nick.mit-license.org/2024) - * @see https://jsr.io/@nick/is@0.2.0-rc.5/doc/positive-zero - */ - import { assertEquals } from "@std/assert"; import { isPositiveZero } from "./positive_zero.ts"; From 7edb5877336caa1c0ca11777539da33b5885b673 Mon Sep 17 00:00:00 2001 From: Nicholas Berlette Date: Sun, 27 Jul 2025 17:10:01 +0000 Subject: [PATCH 11/24] docs: add number and type to docs --- docs/number/even.md | 197 + docs/number/finite-integer.md | 96 + docs/number/finite.md | 117 + docs/number/float.md | 163 + docs/number/float64.md | 160 + docs/number/in-range.md | 378 + docs/number/infinity.md | 167 + docs/number/int16.md | 169 + docs/number/int32.md | 163 + docs/number/int8.md | 152 + docs/number/integer.md | 338 + docs/number/mod.md | 7374 +++++++++++++++++ docs/number/nan.md | 172 + docs/number/negative-finite-integer.md | 101 + docs/number/negative-finite.md | 117 + docs/number/negative-infinity.md | 57 + docs/number/negative-integer.md | 96 + .../number/negative-nonzero-finite-integer.md | 103 + docs/number/negative-nonzero-finite.md | 127 + docs/number/negative-nonzero-integer.md | 101 + docs/number/negative-nonzero.md | 112 + docs/number/negative-zero.md | 164 + docs/number/negative.md | 172 + docs/number/nonzero-finite-integer.md | 101 + docs/number/nonzero-finite.md | 113 + docs/number/nonzero-integer.md | 96 + docs/number/nonzero.md | 154 + docs/number/number.md | 45 + docs/number/odd.md | 203 + docs/number/positive-finite-integer.md | 101 + docs/number/positive-finite.md | 117 + docs/number/positive-infinity.md | 57 + docs/number/positive-integer.md | 96 + .../number/positive-nonzero-finite-integer.md | 103 + docs/number/positive-nonzero-finite.md | 127 + docs/number/positive-nonzero-integer.md | 101 + docs/number/positive-nonzero.md | 128 + docs/number/positive-zero.md | 164 + docs/number/positive.md | 166 + docs/number/types.md | 777 ++ docs/number/uint16.md | 173 + docs/number/uint32.md | 173 + docs/number/uint8.md | 162 + docs/number/zero.md | 116 + docs/type/any-or-never.md | 79 + docs/type/any-or-unknown-or-never.md | 84 + docs/type/any-or-unknown.md | 84 + docs/type/any.md | 113 + docs/type/array.md | 88 + docs/type/assertion.md | 35 + docs/type/boolean.md | 115 + docs/type/exact.md | 59 + docs/type/expect.md | 72 + docs/type/index-signature.md | 104 + docs/type/literal.md | 51 + docs/type/mod.md | 1374 +++ docs/type/never.md | 73 + docs/type/null.md | 71 + docs/type/numeric.md | 50 + docs/type/omit.md | 253 + docs/type/predicate.md | 32 + docs/type/tuple.md | 52 + docs/type/undefined.md | 74 + docs/type/unknown-or-never.md | 80 + docs/type/unknown.md | 159 + 65 files changed, 17171 insertions(+) create mode 100644 docs/number/even.md create mode 100644 docs/number/finite-integer.md create mode 100644 docs/number/finite.md create mode 100644 docs/number/float.md create mode 100644 docs/number/float64.md create mode 100644 docs/number/in-range.md create mode 100644 docs/number/infinity.md create mode 100644 docs/number/int16.md create mode 100644 docs/number/int32.md create mode 100644 docs/number/int8.md create mode 100644 docs/number/integer.md create mode 100644 docs/number/mod.md create mode 100644 docs/number/nan.md create mode 100644 docs/number/negative-finite-integer.md create mode 100644 docs/number/negative-finite.md create mode 100644 docs/number/negative-infinity.md create mode 100644 docs/number/negative-integer.md create mode 100644 docs/number/negative-nonzero-finite-integer.md create mode 100644 docs/number/negative-nonzero-finite.md create mode 100644 docs/number/negative-nonzero-integer.md create mode 100644 docs/number/negative-nonzero.md create mode 100644 docs/number/negative-zero.md create mode 100644 docs/number/negative.md create mode 100644 docs/number/nonzero-finite-integer.md create mode 100644 docs/number/nonzero-finite.md create mode 100644 docs/number/nonzero-integer.md create mode 100644 docs/number/nonzero.md create mode 100644 docs/number/number.md create mode 100644 docs/number/odd.md create mode 100644 docs/number/positive-finite-integer.md create mode 100644 docs/number/positive-finite.md create mode 100644 docs/number/positive-infinity.md create mode 100644 docs/number/positive-integer.md create mode 100644 docs/number/positive-nonzero-finite-integer.md create mode 100644 docs/number/positive-nonzero-finite.md create mode 100644 docs/number/positive-nonzero-integer.md create mode 100644 docs/number/positive-nonzero.md create mode 100644 docs/number/positive-zero.md create mode 100644 docs/number/positive.md create mode 100644 docs/number/types.md create mode 100644 docs/number/uint16.md create mode 100644 docs/number/uint32.md create mode 100644 docs/number/uint8.md create mode 100644 docs/number/zero.md create mode 100644 docs/type/any-or-never.md create mode 100644 docs/type/any-or-unknown-or-never.md create mode 100644 docs/type/any-or-unknown.md create mode 100644 docs/type/any.md create mode 100644 docs/type/array.md create mode 100644 docs/type/assertion.md create mode 100644 docs/type/boolean.md create mode 100644 docs/type/exact.md create mode 100644 docs/type/expect.md create mode 100644 docs/type/index-signature.md create mode 100644 docs/type/literal.md create mode 100644 docs/type/mod.md create mode 100644 docs/type/never.md create mode 100644 docs/type/null.md create mode 100644 docs/type/numeric.md create mode 100644 docs/type/omit.md create mode 100644 docs/type/predicate.md create mode 100644 docs/type/tuple.md create mode 100644 docs/type/undefined.md create mode 100644 docs/type/unknown-or-never.md create mode 100644 docs/type/unknown.md diff --git a/docs/number/even.md b/docs/number/even.md new file mode 100644 index 0000000..45b59c0 --- /dev/null +++ b/docs/number/even.md @@ -0,0 +1,197 @@ +# @nick/is/number/even + +## `isEven` + +#### Signature + +```ts ignore +function isEven(it: T): IsEven; +``` + +Checks if a given number / bigint is an even number. Returns `true` if it is +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :----------------------------------------------------------------- | +| **`it`** | The number or bigint to check, either literal or in string format. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEven` + +#### Signature + +```ts ignore +function isEven(it: number | `${number}`): it is Even; +``` + +Checks if a given number / numeric string is even. Returns `true` if the value +is divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------- | +| **`it`** | The number or numeric string to check. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEven` + +#### Signature + +```ts ignore +function isEven(it: bigint | `${bigint}`): it is Even; +``` + +Checks if a given bigint or bigint string is an even number. Returns `true` if +the value is divisible by `2`, and `false` otherwise. This usually corresponds +to integers that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------ | +| **`it`** | The bigint or bigint string to check. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEven` + +#### Signature + +```ts ignore +function isEven(it: unknown): it is Even; +``` + +Checks if a given number / bigint is even. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an even finite integer, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `Even` + +#### Signature + +```ts ignore +export type Even = Cast; +``` + +Branded type representing an even number or bigint. Used by overloads of the +[`isEven`](#iseven "Jump to symbol: 'isEven'") function to differentiate between +odd and even numbers. + +##### Type Parameters + +- **`T`** extends `Numeric` (default: `Numeric`) + +--- + +###### Category + +`Numeric` + +## `IsEven` + +#### Signature + +```ts ignore +export type IsEven = `${T}` extends + `${"" | bigint}${1 | 3 | 5 | 7 | 9}` ? True : False; +``` + +Type-level equivalent of [`isEven`](#iseven "Jump to symbol: 'isEven'"), which +checks if a given numeric type (number or bigint) ends in an even number. +Returns [True](#true "Jump to symbol: 'True'") if so, and +[False](#false "Jump to symbol: 'False'") otherwise. + +##### Type Parameters + +- **`T`** extends `Numeric` +- **`True`** (default: `T`) +- **`False`** (default: `never`) + +--- + +###### Category + +`Numeric` diff --git a/docs/number/finite-integer.md b/docs/number/finite-integer.md new file mode 100644 index 0000000..e4df491 --- /dev/null +++ b/docs/number/finite-integer.md @@ -0,0 +1,96 @@ +# @nick/is/number/finite-integer + +## `isFiniteInteger` + +#### Signature + +```ts ignore +function isFiniteInteger(it: N): it is FiniteInteger; +``` + +Checks if a given value is a finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isFiniteInteger(0)); // true +console.log(isFiniteInteger(1)); // true +console.log(isFiniteInteger(-1)); // true +console.log(isFiniteInteger(1.5)); // false +console.log(isFiniteInteger(NaN)); // false +console.log(isFiniteInteger(Infinity)); // false +``` + +## `isFiniteInteger` + +#### Signature + +```ts ignore +function isFiniteInteger(it: unknown): it is FiniteInteger; +``` + +Checks if a given value is a finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isFiniteInteger(0)); // true +console.log(isFiniteInteger(1)); // true +console.log(isFiniteInteger(-1)); // true +console.log(isFiniteInteger(1.5)); // false +console.log(isFiniteInteger(NaN)); // false +console.log(isFiniteInteger(Infinity)); // false +``` + +## `FiniteInteger` + +#### Signature + +```ts ignore +export type FiniteInteger = Cast; +``` + +Casts a value into a finite integer type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/finite.md b/docs/number/finite.md new file mode 100644 index 0000000..431261b --- /dev/null +++ b/docs/number/finite.md @@ -0,0 +1,117 @@ +# @nick/is/number/finite + +## `isFinite` + +#### Signature + +```ts ignore +function isFinite(it: N): it is Finite; +``` + +Checks if a given value is a finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFinite } from "jsr:@nick/is/integer"; + +console.log(isFinite(0)); // true +console.log(isFinite(1)); // true +console.log(isFinite(-1)); // true +console.log(isFinite(1.5)); // true +console.log(isFinite(NaN)); // false +console.log(isFinite(Infinity)); // false +``` + +## `isFinite` + +#### Signature + +```ts ignore +function isFinite(it: unknown): it is Finite; +``` + +Checks if a given value is a finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFinite } from "jsr:@nick/is/integer"; + +console.log(isFinite(0)); // true +console.log(isFinite(1)); // true +console.log(isFinite(-1)); // true +console.log(isFinite(1.5)); // true +console.log(isFinite(NaN)); // false +console.log(isFinite(Infinity)); // false +``` + +## `Finite` + +#### Signature + +```ts ignore +export type Finite = Cast; +``` + +Casts a value into a finite type. If the value is not a number, it will resolve +to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeFinite` + +#### Signature + +```ts ignore +export type MaybeFinite = Cast; +``` + +Casts a value into a partial finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/float.md b/docs/number/float.md new file mode 100644 index 0000000..3e8821f --- /dev/null +++ b/docs/number/float.md @@ -0,0 +1,163 @@ +# @nick/is/number/float + +## `isFloat` + +#### Signature + +```ts ignore +function isFloat(it: N): it is Float; +``` + +Checks if the value is a floating-point number. Supports both single and double +precision floating-point numbers. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a floating-point number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat } from "@nick/is/float"; + +isFloat(1); // false +isFloat(1.0); // false +isFloat(1.1); // true +isFloat(1.00001e1); // true +``` + +## `isFloat` + +#### Signature + +```ts ignore +function isFloat(it: unknown): it is Float; +``` + +Checks if the value is a floating-point number. Supports both single and double +precision floating-point numbers. + +## Rules for what is (and isn't) seen as a floating-point number + +- `0`, `-0` are considered valid floating-point numbers, and return `true`. +- `1`, `-1` and other integers (or _"non-floating"_ values) return `false`. +- Special cases like `Infinity`, `-Infinity`, and `NaN` return `false`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a floating-point number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat } from "@nick/is/float"; + +isFloat(0); // true +isFloat(1); // false +isFloat(1.0); // false +isFloat(1.1); // true +isFloat(1.00001e1); // true +``` + +## `Float` + +#### Signature + +```ts ignore +export type Float = Cast; +``` + +Casts a value into a floating-point type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float` `number` + +#### Examples + +```ts +import { type Float, isFloat } from "@nick/is/float"; + +let x = 1.5 as Float, y = 0; + +if (isFloat(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float'. +``` + +## `MaybeFloat` + +#### Signature + +```ts ignore +export type MaybeFloat = Cast; +``` + +Casts a value into a partial floating-point type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float` `number` + +#### Examples + +```ts +import { isFloat, type MaybeFloat } from "@nick/is/float"; + +let x = 1.5 as MaybeFloat, y = 0; + +if (isFloat(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Float`) +``` diff --git a/docs/number/float64.md b/docs/number/float64.md new file mode 100644 index 0000000..82d6cf4 --- /dev/null +++ b/docs/number/float64.md @@ -0,0 +1,160 @@ +# @nick/is/number/float64 + +## `isFloat64` + +#### Signature + +```ts ignore +function isFloat64(it: N): it is Float64; +``` + +Checks if the value is a float64-precision floating-point number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a float64-precision floating-point number, `false` +otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat64 } from "jsr:@nick/is/float64"; + +console.log(isFloat64(1.5)); // true +console.log(isFloat64(0)); // false +console.log(isFloat64(1)); // false +console.log(isFloat64(-1)); // false +console.log(isFloat64(NaN)); // false +console.log(isFloat64(Infinity)); // false +``` + +## `isFloat64` + +#### Signature + +```ts ignore +function isFloat64(it: unknown): it is Float64; +``` + +Checks if the value is a float64-precision floating-point number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a float64-precision floating-point number, `false` +otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat64 } from "jsr:@nick/is/float64"; + +console.log(isFloat64(1.5)); // true +console.log(isFloat64(0)); // false +console.log(isFloat64(1)); // false +console.log(isFloat64(-1)); // false +console.log(isFloat64(NaN)); // false +console.log(isFloat64(Infinity)); // false +``` + +## `Float64` + +#### Signature + +```ts ignore +export type Float64 = Cast; +``` + +Casts a value into a float64-precision floating-point type. If the value is not +a number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float64` `number` + +#### Examples + +```ts +import { type Float64, isFloat64 } from "jsr:@type/number/float64"; + +let x = 1.5 as Float64, y = 0; + +if (isFloat64(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float64'. +``` + +## `MaybeFloat64` + +#### Signature + +```ts ignore +export type MaybeFloat64 = Cast; +``` + +Casts a value into a partial float64-precision floating-point type. If the value +is not a number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float64` `number` + +#### Examples + +```ts +import { isFloat64, type MaybeFloat64 } from "jsr:@type/number/float64"; + +let x = 1.5 as MaybeFloat64, y = 0; + +if (isFloat64(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Float64`) +``` diff --git a/docs/number/in-range.md b/docs/number/in-range.md new file mode 100644 index 0000000..77fb029 --- /dev/null +++ b/docs/number/in-range.md @@ -0,0 +1,378 @@ +# @nick/is/number/in-range + +## `inRange` + +#### Signature + +```ts ignore +function inRange< + V extends number, + R extends Derange, + Min extends number = R extends [infer M extends number, number, Exclusivity?] + ? M + : R[1] extends Exclusivity ? 0 + : R[0], + Max extends number = R extends [number, infer M extends number, Exclusivity?] + ? M + : R[1] extends Exclusivity ? R[0] + : R[1], + Tex extends Exclusivity = Either< + R extends [number, number, infer T extends Exclusivity] ? T + : R[1] extends Exclusivity ? R[1] + : undefined, + "[)" + >, +>(value: V, ...range: [...R] | Derange): value is InRange; +``` + +Checks if a given number is within a given range. The range can be specified in +multiple ways: + +- As a tuple with the minimum and maximum values, and optional exclusivity + string of either "[]", "(]", "[)", or "()". +- As a tuple with a maximum value and an optional exclusivity string. This + assumes a minimum value of `0`. +- As a single number, which is assumed to be the maximum value, with an assumed + minimum value of `0` and an assumed exclusivity string of "[]". + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------- | +| **`value`** | The number to check. | +| **`range`** | The range to check against. | + +##### Returns + +`true` if the number is within the range, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { inRange } from "jsr:@nick/is/number/in_range"; + +console.log(inRange(1, 0, 2)); // true +console.log(inRange(1, 2, 0)); // false +console.log(inRange(1, 2)); // true +console.log(inRange(1, 2, "(]")); // true +``` + +## `inRange` + +#### Signature + +```ts ignore +function inRange(value: number, ...range: Derange): value is InRange; +``` + +Checks if a given number is within a given range. The range can be specified in +multiple ways: + +- As a tuple with the minimum and maximum values, and optional exclusivity + string of either "[]", "(]", "[)", or "()". +- As a tuple with a maximum value and an optional exclusivity string. This + assumes a minimum value of `0`. +- As a single number, which is assumed to be the maximum value, with an assumed + minimum value of `0` and an assumed exclusivity string of "[]". + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------- | +| **`value`** | The number to check. | +| **`range`** | The range to check against. | + +##### Returns + +`true` if the number is within the range, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { inRange } from "jsr:@nick/is/number/in_range"; + +console.log(inRange(1, 0, 2)); // true +console.log(inRange(1, 2, 0)); // false +console.log(inRange(1, 2)); // true +console.log(inRange(1, 2, "(]")); // true +``` + +## `inRange` + +#### Signature + +```ts ignore +function inRange(value: number, ...range: any[]): undefined; +``` + +## `isExclusivity` + +#### Signature + +```ts ignore +function isExclusivity(it: unknown): it is Exclusivity; +``` + +Checks if a given value is a valid range exclusivity string (either "[]", "(]", +"[)", or "()"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a valid range exclusivity string, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isExclusivity } from "jsr:@nick/is/number/in_range"; + +console.log(isExclusivity("[]")); // true +console.log(isExclusivity("(]")); // true +console.log(isExclusivity("[)")); // true +console.log(isExclusivity("()")); // true +console.log(isExclusivity("")); // false +console.log(isExclusivity("[")); // false +console.log(isExclusivity("]")); // false +``` + +## `AnyRange` + +#### Signature + +```ts ignore +export type AnyRange = + | RangeInclusiveMin + | RangeInclusive + | RangeInclusiveMax + | RangeExclusive; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `Derange` + +#### Signature + +```ts ignore +export type Derange = + | readonly [number, number, "[]"] + | readonly [number, "[]"] + | readonly [number, number, "[)"] + | readonly [number, "[)"] + | readonly [number, number, "(]"] + | readonly [number, "(]"] + | readonly [number, number, "()"] + | readonly [number, "()"] + | readonly [number, number, Exclusivity] + | readonly [number, Exclusivity]; +``` + +## `Exclusivity` + +#### Signature + +```ts ignore +export type Exclusivity = AnyRange[2]; +``` + +## `InRange` + +#### Signature + +```ts ignore +export type InRange< + N extends number, + Min extends number = number, + Max extends number = number, + Tex extends Exclusivity = Exclusivity, +> = + & (number extends N ? IsInRange + : `${Min}|${Max}` extends `-${number}|-${number}` + ? `${N}` extends `-${number}` ? IsInRange : never + : `${Min}|${Max}` extends `${number}|-${number}` ? never + : `${Min}|${Max}` extends `-${number}|${number}` + ? `${N}` extends `-${number}` ? IsInRange : never + : `${N}` extends `-${number}` ? never + : IsInRange) + & N; +``` + +Type-level equivalent to the [`inRange`](#inrange "Jump to symbol: 'inRange'") +function, which (naively) checks if a number is within a given range. The range +can be specified in multiple ways, with one of four different exclusivity types. + +##### Type Parameters + +- **`N`** extends `number` +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `Exclusivity`) + +--- + +###### See Also + +- [`inRange`](#inrange "Jump to symbol: 'inRange'") for more information. + +## `Range` + +#### Signature + +```ts ignore +export type Range< + Min extends number = number, + Max extends number = number, + Tex extends Exclusivity = never, +> = [Tex] extends [never] ? + | RangeInclusiveMin + | RangeInclusive + | RangeInclusiveMax + | RangeExclusive + | RangeUnknown + : Either< + Extract, Required>>, + RangeUnknown + >; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `never`) + +--- + +## `RangeExclusive` + +#### Signature + +```ts ignore +export type RangeExclusive< + Min extends number = number, + Max extends number = number, +> = readonly [Min, Max, "()"] | readonly [Max, "()"]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `RangeInclusive` + +#### Signature + +```ts ignore +export type RangeInclusive< + Min extends number = number, + Max extends number = number, +> = readonly [Min, Max, "[]"] | readonly [Max, "[]"]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `RangeInclusiveMax` + +#### Signature + +```ts ignore +export type RangeInclusiveMax< + Min extends number = number, + Max extends number = number, +> = readonly [Min, Max, "(]"] | readonly [Max, "(]"]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `RangeInclusiveMin` + +#### Signature + +```ts ignore +export type RangeInclusiveMin< + Min extends number = number, + Max extends number = number, +> = readonly [Min, Max, "[)"] | readonly [Max, "[)"]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `RangeUnknown` + +#### Signature + +```ts ignore +export type RangeUnknown< + Min extends number = number, + Max extends number = number, + Tex extends Exclusivity = Exclusivity, +> = readonly [Min, Max, Tex] | readonly [Max, Tex]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `Exclusivity`) + +--- + +## `IsInRange` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `Exclusivity`) + +--- + +### Properties + +#### RANGE + +```ts +readonly RANGE: readonly [Min,Max,Tex]; +``` + +--- diff --git a/docs/number/infinity.md b/docs/number/infinity.md new file mode 100644 index 0000000..f0f2501 --- /dev/null +++ b/docs/number/infinity.md @@ -0,0 +1,167 @@ +# @nick/is/number/infinity + +## `isInfinity` + +#### Signature + +```ts ignore +function isInfinity(it: unknown): it is Infinity; +``` + +Checks if a given value is a non-finite number (`Infinity` or `-Infinity`). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a non-finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInfinity } from "@nick/is/number/infinity"; + +console.log(isInfinity(Infinity)); // true +console.log(isInfinity(-Infinity)); // true +console.log(isInfinity(1)); // false +console.log(isInfinity(-1)); // false +console.log(isInfinity(NaN)); // false +``` + +## `isNegativeInfinity` + +#### Signature + +```ts ignore +function isNegativeInfinity(it: unknown): it is NegativeInfinity; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is negative infinity, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `negative` `infinity` + +#### Examples + +```ts +import { isNegativeInfinity } from "@nick/is/number/infinity"; + +console.log(isNegativeInfinity(Infinity)); // false +console.log(isNegativeInfinity(-Infinity)); // true +console.log(isNegativeInfinity(1)); // false +console.log(isNegativeInfinity(-1)); // false +console.log(isNegativeInfinity(NaN)); // false +``` + +## `isPositiveInfinity` + +#### Signature + +```ts ignore +function isPositiveInfinity(it: unknown): it is PositiveInfinity; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is positive infinity, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `positive` `infinity` + +#### Examples + +```ts +import { isPositiveInfinity } from "@nick/is/number/infinity"; + +console.log(isPositiveInfinity(Infinity)); // false +console.log(isPositiveInfinity(-Infinity)); // true +console.log(isPositiveInfinity(1)); // false +console.log(isPositiveInfinity(-1)); // false +console.log(isPositiveInfinity(NaN)); // false +``` + +## `Infinity` + +#### Signature + +```ts ignore +export type Infinity = PositiveInfinity | NegativeInfinity; +``` + +Special type representing either positive or negative infinity. + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` + +## `NegativeInfinity` + +#### Signature + +```ts ignore +export type NegativeInfinity = -Infinity; +``` + +Special type representing negative infinity (`Number.NEGATIVE_INFINITY`). + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` `negative` + +## `PositiveInfinity` + +#### Signature + +```ts ignore +export type PositiveInfinity = Infinity; +``` + +Special type representing positive infinity (`Number.POSITIVE_INFINITY`). + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` `positive` diff --git a/docs/number/int16.md b/docs/number/int16.md new file mode 100644 index 0000000..45388bd --- /dev/null +++ b/docs/number/int16.md @@ -0,0 +1,169 @@ +# @nick/is/number/int16 + +## `isInt16` + +#### Signature + +```ts ignore +function isInt16(it: unknown): it is Int16; +``` + +Checks if a value is a 16-bit integer (between -32768 and 32767). + +To check for an **unsigned** 16-bit integer (0-65535), use +[isUint16](#isuint16 "Jump to symbol: 'isUint16'"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/number"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -32769; // <- TS2322 Type '-32769' is not assignable to type 'Int16'. +``` + +## `isInt16` + +#### Signature + +```ts ignore +function isInt16(it: unknown): it is Int16; +``` + +Checks if a value is a 16-bit integer (between -32768 and 32767). + +To check for an **unsigned** 16-bit integer (0-65535), use +[isUint16](#isuint16 "Jump to symbol: 'isUint16'"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInt16 } from "@nick/is/number"; + +isInt16(32768); // false +isInt16(-32769); // false +isInt16(1); // true +isInt16(32767); // true +isInt16(-32768); // true +``` + +## `Int16` + +#### Signature + +```ts ignore +export type Int16 = Cast; +``` + +Casts a value into a signed 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/int16"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -32769; // <- TS2322 Type '-32769' is not assignable to type 'Int16'. +``` + +## `MaybeInt16` + +#### Signature + +```ts ignore +export type MaybeInt16 = Cast; +``` + +Casts a value into a partial signed 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/int16"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +value = -32769; // Error: Type '-32769' is not assignable to type 'Int16'. +``` diff --git a/docs/number/int32.md b/docs/number/int32.md new file mode 100644 index 0000000..1545dc8 --- /dev/null +++ b/docs/number/int32.md @@ -0,0 +1,163 @@ +# @nick/is/number/int32 + +## `isInt32` + +#### Signature + +```ts ignore +function isInt32(it: N): it is Int32; +``` + +Checks if a given value is a signed 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a signed 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`int32` `number` + +#### Examples + +```ts +import { type Int32, isInt32, type MaybeInt32 } from "jsr:@type/number/int32"; + +let value = 1 as Int32; + +const setValue = (newValue: MaybeInt32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -2147483649; // <- TS2322 Type '-2147483649' is not assignable to type 'Int32'. +``` + +## `isInt32` + +#### Signature + +```ts ignore +function isInt32(it: unknown): it is Int32; +``` + +Checks if a given value is a signed 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a signed 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`int32` `number` + +#### Examples + +```ts +import { isInt32 } from "jsr:@type/number/int32"; + +console.log(isInt32(0x7FFFFFFF)); // <- true +console.log(isInt32(-2147483649)); // <- false +``` + +## `Int32` + +#### Signature + +```ts ignore +export type Int32 = Cast; +``` + +Casts a value into a signed 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int32` `number` + +#### Examples + +```ts +import { type Int32, isInt32 } from "jsr:@type/number/int32"; + +let value = 1 as Int32; + +const setValue = (newValue: Int32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -2147483649; // <- TS2322 Type '-2147483649' is not assignable to type 'Int32'. +``` + +## `MaybeInt32` + +#### Signature + +```ts ignore +export type MaybeInt32 = Cast; +``` + +Casts a value into a partial signed 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int32` `number` + +#### Examples + +```ts +import { isInt32, type MaybeInt32 } from "jsr:@type/number/int32"; + +let value = 1 as MaybeInt32; + +const setValue = (newValue: MaybeInt32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! +value = -2147483649; // <- No error! (this is the main difference from `Int32`) +``` diff --git a/docs/number/int8.md b/docs/number/int8.md new file mode 100644 index 0000000..547f3f7 --- /dev/null +++ b/docs/number/int8.md @@ -0,0 +1,152 @@ +# @nick/is/number/int8 + +## `isInt8` + +#### Signature + +```ts ignore +function isInt8(it: N): it is Int8; +``` + +Checks if a given value is a signed 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a signed 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInt8 } from "@nick/is/int8"; + +isInt8(1); // true +isInt8(1.0); // false +isInt8(1.1); // false +isInt8(1.00001e1); // false +``` + +## `isInt8` + +#### Signature + +```ts ignore +function isInt8(it: unknown): it is Int8; +``` + +Checks if a given value is a signed 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a signed 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInt8 } from "@nick/is/int8"; + +console.log(isInt8(1)); // true +console.log(isInt8(1.0)); // false +console.log(isInt8(1.1)); // false +console.log(isInt8(1.00001e1)); // false +``` + +## `Int8` + +#### Signature + +```ts ignore +export type Int8 = Cast; +``` + +Casts a value into a signed 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int8` `number` + +#### Examples + +```ts +import { type Int8, isInt8 } from "@nick/is/int8"; + +let i = 1 as Int8, y = 0; + +if (isInt8(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = 1.5; // <- TS2322 Type '1.5' is not assignable to type 'Int8'. +``` + +## `MaybeInt8` + +#### Signature + +```ts ignore +export type MaybeInt8 = Cast; +``` + +Casts a value into a partial signed 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int8` `number` + +#### Examples + +```ts +import { isInt8, type MaybeInt8 } from "@nick/is/int8"; + +let i = 1 as MaybeInt8, y = 0; + +if (isInt8(i)) { + console.log(i); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Int8`) +``` diff --git a/docs/number/integer.md b/docs/number/integer.md new file mode 100644 index 0000000..e5ed0b3 --- /dev/null +++ b/docs/number/integer.md @@ -0,0 +1,338 @@ +# @nick/is/number/integer + +## `isInteger` + +#### Signature + +```ts ignore +function isInteger(it: N): it is Integer; +``` + +Checks if a given value is an integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInteger } from "jsr:@nick/is/integer"; + +console.log(isInteger(0)); // true +console.log(isInteger(1)); // true +console.log(isInteger(-1)); // true +console.log(isInteger(1.5)); // false +console.log(isInteger(NaN)); // false +console.log(isInteger(Infinity)); // false +``` + +## `isInteger` + +#### Signature + +```ts ignore +function isInteger(it: unknown): it is Integer; +``` + +Checks if a given value is an integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInteger } from "jsr:@nick/is/integer"; + +console.log(isInteger(0)); // true +console.log(isInteger(1)); // true +console.log(isInteger(-1)); // true +console.log(isInteger(1.5)); // false +console.log(isInteger(NaN)); // false +console.log(isInteger(Infinity)); // false +``` + +## `BigInteger` + +#### Signature + +```ts ignore +export type BigInteger = CastInt; +``` + +Casts a value into a big integer type (which is really just a bigint). If the +value is not a bigint or a string containing a valid integer, it will resolve to +`never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `Cast` + +#### Signature + +```ts ignore +export type Cast = Extract & T; +``` + +Casts a value into a specific numeric type. If the value is not a number, it +will resolve to `never`, indicating its incompatibility with the type. + +This is a low-level utility type that primarily serves as an internal helper for +more user-friendly types like [Integer](#integer "Jump to symbol: 'Integer'") +and [Positive](#positive "Jump to symbol: 'Positive'"). Unless you're building +custom numeric types with your own branding, you most likely never directly +handle this type in the wild. + +##### Type Parameters + +- **`N`** +- **`T`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { Cast } from "jsr:@nick/is/number"; + +declare const MY_DOUBLE: unique symbol; +type DOUBLE = Cast; + +let x = 4.3210123210 as DOUBLE; +let y = 3.1415926535 as DOUBLE; + +console.log(x + y); // 7.4626049745 + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'DOUBLE'. +``` + +## `Integer` + +#### Signature + +```ts ignore +export type Integer = N extends bigint + ? `${N}` extends `${infer I extends number}` ? N & Integer : never + : N extends number ? number extends N ? N & INTEGER + : `${N}` extends `${bigint}` ? N & INTEGER + : never + : never; +``` + +Casts a value into an integer type. If the value is not an number, or is a +non-integral number like 3.14, it will resolve to `never`. + +**Note**: once a value is cast to a type with this narrow of a constraint, +TypeScript's compiler will refuse any assignment to it that is not _exactly_ +compatible with the type. If you find yourself encountering errors about +incompatible types, try using the +[MaybeInteger](#maybeinteger "Jump to symbol: 'MaybeInteger'") type instead. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { type Integer, isInteger } from "jsr:@type/number"; + +function add(a: Integer, b: Integer) { + return (a + b) as Integer; +} + +let x = 1 as Integer, y = 2 as Integer, z = 3; + +if (isInteger(z)) { + console.log(add(add(x, y), z)); +} else { + console.log(add(x, y)); +} + +// These will raise TypeScript compiler errors: +add(x, z); +add(y, 3); + +// This level of strictness can be a bit silly in the wrong application: +x = 1; // <- TS4321 (`MaybeInteger` would be a better choice here) +``` + +## `MaybeInteger` + +#### Signature + +```ts ignore +export type MaybeInteger = N extends bigint + ? `${N}` extends `${infer I extends number}` ? N & MaybeInteger : never + : N extends number ? number extends N ? N & MAYBE_INTEGER + : `${N}` extends `${bigint}` ? N & MAYBE_INTEGER + : never + : never; +``` + +Casts a value into a partial integer type. If the value is not an number, or is +a non-integral number like 3.14, it will resolve to `never`. This type is nearly +identical to [Integer](#integer "Jump to symbol: 'Integer'"), except it allows +assignment of values that are not precisely compatible with the type, while +still providing an extra level of type safety over the base `number` type. + +Once a value is cast to a type of this constraint, TypeScript's compiler will +refuse any incompatible assignment to it. To demonstrate, consider this example: + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { + isInteger, + type MaybeFloat, + type MaybeInteger, +} from "jsr:@type/number"; + +function add(a: MaybeInteger, b: MaybeInteger) { + return (a + b) as MaybeInteger; +} + +let x = 1 as MaybeInteger, y = 2 as MaybeInteger, z = 3; +let xx = 1.1 as MaybeFloat, yy = 2.2 as MaybeFloat, zz = 3.3; + +if (isInteger(z)) { + console.log(add(add(x, y), z)); +} else { + console.log(add(x, y)); +} + +// These will raise TypeScript compiler errors: +add(x, yy); // <- TS2345 Type 'MaybeFloat' is not assignable to type 'MaybeInteger'. +y = yy; // <- TS2322 Type 'MaybeFloat' is not assignable to type 'MaybeInteger'. + +y = 2; // <- No error! (this is the main difference from `Integer`) +``` + +## `NegativeBigInteger` + +#### Signature + +```ts ignore +export type NegativeBigInteger = CastInt; +``` + +Casts a value into a negative big integer type. If the value is not a bigint or +a string containing a valid integer, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `PositiveBigInteger` + +#### Signature + +```ts ignore +export type PositiveBigInteger = CastInt; +``` + +Casts a value into a positive big integer type. If the value is not a bigint or +a string containing a valid integer, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `Unwrap` + +#### Signature + +```ts ignore +export type Unwrap = U extends Cast ? [N, T] : [U, never]; +``` + +Unwraps a type that has been cast with [Cast](#cast "Jump to symbol: 'Cast'") +into a tuple of the original value and the specific type it was cast to (or +"branded" with). If the given type was _not_ cast with +[Cast](#cast "Jump to symbol: 'Cast'"), it will resolve to a tuple containing +the original value and `never`, respectively. + +##### Type Parameters + +- **`U`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { Cast, Unwrap } from "jsr:@nick/is/number"; + +type Int_3 = Cast<3, INTEGER>; + +function unwrap(value: T): Unwrap[0] { + return value as Unwrap[0]; +} +``` diff --git a/docs/number/mod.md b/docs/number/mod.md new file mode 100644 index 0000000..579b0d4 --- /dev/null +++ b/docs/number/mod.md @@ -0,0 +1,7374 @@ +# @nick/is/number/mod + +## `inRange` + +#### Signature + +```ts ignore +function inRange< + V extends number, + R extends Derange, + Min extends number = R extends [infer M extends number, number, Exclusivity?] + ? M + : R[1] extends Exclusivity ? 0 + : R[0], + Max extends number = R extends [number, infer M extends number, Exclusivity?] + ? M + : R[1] extends Exclusivity ? R[0] + : R[1], + Tex extends Exclusivity = Either< + R extends [number, number, infer T extends Exclusivity] ? T + : R[1] extends Exclusivity ? R[1] + : undefined, + "[)" + >, +>(value: V, ...range: [...R] | Derange): value is InRange; +``` + +Checks if a given number is within a given range. The range can be specified in +multiple ways: + +- As a tuple with the minimum and maximum values, and optional exclusivity + string of either "[]", "(]", "[)", or "()". +- As a tuple with a maximum value and an optional exclusivity string. This + assumes a minimum value of `0`. +- As a single number, which is assumed to be the maximum value, with an assumed + minimum value of `0` and an assumed exclusivity string of "[]". + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------- | +| **`value`** | The number to check. | +| **`range`** | The range to check against. | + +##### Returns + +`true` if the number is within the range, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { inRange } from "jsr:@nick/is/number/in_range"; + +console.log(inRange(1, 0, 2)); // true +console.log(inRange(1, 2, 0)); // false +console.log(inRange(1, 2)); // true +console.log(inRange(1, 2, "(]")); // true +``` + +## `inRange` + +#### Signature + +```ts ignore +function inRange(value: number, ...range: Derange): value is InRange; +``` + +Checks if a given number is within a given range. The range can be specified in +multiple ways: + +- As a tuple with the minimum and maximum values, and optional exclusivity + string of either "[]", "(]", "[)", or "()". +- As a tuple with a maximum value and an optional exclusivity string. This + assumes a minimum value of `0`. +- As a single number, which is assumed to be the maximum value, with an assumed + minimum value of `0` and an assumed exclusivity string of "[]". + +##### Parameters + +| Name | Info | +| :---------- | :-------------------------- | +| **`value`** | The number to check. | +| **`range`** | The range to check against. | + +##### Returns + +`true` if the number is within the range, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { inRange } from "jsr:@nick/is/number/in_range"; + +console.log(inRange(1, 0, 2)); // true +console.log(inRange(1, 2, 0)); // false +console.log(inRange(1, 2)); // true +console.log(inRange(1, 2, "(]")); // true +``` + +## `inRange` + +#### Signature + +```ts ignore +function inRange(value: number, ...range: any[]): undefined; +``` + +## `isEven` + +#### Signature + +```ts ignore +function isEven(it: T): IsEven; +``` + +Checks if a given number / bigint is an even number. Returns `true` if it is +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :----------------------------------------------------------------- | +| **`it`** | The number or bigint to check, either literal or in string format. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEven` + +#### Signature + +```ts ignore +function isEven(it: number | `${number}`): it is Even; +``` + +Checks if a given number / numeric string is even. Returns `true` if the value +is divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------- | +| **`it`** | The number or numeric string to check. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEven` + +#### Signature + +```ts ignore +function isEven(it: bigint | `${bigint}`): it is Even; +``` + +Checks if a given bigint or bigint string is an even number. Returns `true` if +the value is divisible by `2`, and `false` otherwise. This usually corresponds +to integers that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------ | +| **`it`** | The bigint or bigint string to check. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEven` + +#### Signature + +```ts ignore +function isEven(it: unknown): it is Even; +``` + +Checks if a given number / bigint is even. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an even finite integer, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEvenNumber` + +#### Signature + +```ts ignore +function isEvenNumber(it: T): IsEven; +``` + +Checks if a given number / bigint is an even number. Returns `true` if it is +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :----------------------------------------------------------------- | +| **`it`** | The number or bigint to check, either literal or in string format. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEvenNumber` + +#### Signature + +```ts ignore +function isEvenNumber(it: number | `${number}`): it is Even; +``` + +Checks if a given number / numeric string is even. Returns `true` if the value +is divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------- | +| **`it`** | The number or numeric string to check. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEvenNumber` + +#### Signature + +```ts ignore +function isEvenNumber(it: bigint | `${bigint}`): it is Even; +``` + +Checks if a given bigint or bigint string is an even number. Returns `true` if +the value is divisible by `2`, and `false` otherwise. This usually corresponds +to integers that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------ | +| **`it`** | The bigint or bigint string to check. | + +##### Returns + +`true` if the value is even, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isEvenNumber` + +#### Signature + +```ts ignore +function isEvenNumber(it: unknown): it is Even; +``` + +Checks if a given number / bigint is even. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `0`, `2`, `4`, `6`, or `8`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an even finite integer, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isEven } from "@nick/is/even"; + +isEven(0); // true +isEven(1); // false +isEven(2n); // true +isEven(3n); // false +``` + +## `isExclusivity` + +#### Signature + +```ts ignore +function isExclusivity(it: unknown): it is Exclusivity; +``` + +Checks if a given value is a valid range exclusivity string (either "[]", "(]", +"[)", or "()"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a valid range exclusivity string, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isExclusivity } from "jsr:@nick/is/number/in_range"; + +console.log(isExclusivity("[]")); // true +console.log(isExclusivity("(]")); // true +console.log(isExclusivity("[)")); // true +console.log(isExclusivity("()")); // true +console.log(isExclusivity("")); // false +console.log(isExclusivity("[")); // false +console.log(isExclusivity("]")); // false +``` + +## `isFinite` + +#### Signature + +```ts ignore +function isFinite(it: N): it is Finite; +``` + +Checks if a given value is a finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFinite } from "jsr:@nick/is/integer"; + +console.log(isFinite(0)); // true +console.log(isFinite(1)); // true +console.log(isFinite(-1)); // true +console.log(isFinite(1.5)); // true +console.log(isFinite(NaN)); // false +console.log(isFinite(Infinity)); // false +``` + +## `isFinite` + +#### Signature + +```ts ignore +function isFinite(it: unknown): it is Finite; +``` + +Checks if a given value is a finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFinite } from "jsr:@nick/is/integer"; + +console.log(isFinite(0)); // true +console.log(isFinite(1)); // true +console.log(isFinite(-1)); // true +console.log(isFinite(1.5)); // true +console.log(isFinite(NaN)); // false +console.log(isFinite(Infinity)); // false +``` + +## `isFiniteInteger` + +#### Signature + +```ts ignore +function isFiniteInteger(it: N): it is FiniteInteger; +``` + +Checks if a given value is a finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isFiniteInteger(0)); // true +console.log(isFiniteInteger(1)); // true +console.log(isFiniteInteger(-1)); // true +console.log(isFiniteInteger(1.5)); // false +console.log(isFiniteInteger(NaN)); // false +console.log(isFiniteInteger(Infinity)); // false +``` + +## `isFiniteInteger` + +#### Signature + +```ts ignore +function isFiniteInteger(it: unknown): it is FiniteInteger; +``` + +Checks if a given value is a finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isFiniteInteger(0)); // true +console.log(isFiniteInteger(1)); // true +console.log(isFiniteInteger(-1)); // true +console.log(isFiniteInteger(1.5)); // false +console.log(isFiniteInteger(NaN)); // false +console.log(isFiniteInteger(Infinity)); // false +``` + +## `isFiniteNumber` + +#### Signature + +```ts ignore +function isFiniteNumber(it: N): it is Finite; +``` + +Checks if a given value is a finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFinite } from "jsr:@nick/is/integer"; + +console.log(isFinite(0)); // true +console.log(isFinite(1)); // true +console.log(isFinite(-1)); // true +console.log(isFinite(1.5)); // true +console.log(isFinite(NaN)); // false +console.log(isFinite(Infinity)); // false +``` + +## `isFiniteNumber` + +#### Signature + +```ts ignore +function isFiniteNumber(it: unknown): it is Finite; +``` + +Checks if a given value is a finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFinite } from "jsr:@nick/is/integer"; + +console.log(isFinite(0)); // true +console.log(isFinite(1)); // true +console.log(isFinite(-1)); // true +console.log(isFinite(1.5)); // true +console.log(isFinite(NaN)); // false +console.log(isFinite(Infinity)); // false +``` + +## `isFloat` + +#### Signature + +```ts ignore +function isFloat(it: N): it is Float; +``` + +Checks if the value is a floating-point number. Supports both single and double +precision floating-point numbers. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a floating-point number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat } from "@nick/is/float"; + +isFloat(1); // false +isFloat(1.0); // false +isFloat(1.1); // true +isFloat(1.00001e1); // true +``` + +## `isFloat` + +#### Signature + +```ts ignore +function isFloat(it: unknown): it is Float; +``` + +Checks if the value is a floating-point number. Supports both single and double +precision floating-point numbers. + +## Rules for what is (and isn't) seen as a floating-point number + +- `0`, `-0` are considered valid floating-point numbers, and return `true`. +- `1`, `-1` and other integers (or _"non-floating"_ values) return `false`. +- Special cases like `Infinity`, `-Infinity`, and `NaN` return `false`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a floating-point number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat } from "@nick/is/float"; + +isFloat(0); // true +isFloat(1); // false +isFloat(1.0); // false +isFloat(1.1); // true +isFloat(1.00001e1); // true +``` + +## `isFloat16` + +#### Signature + +```ts ignore +function isFloat16(it: N): it is Float16; +``` + +Checks if a value is a 16-bit half-precision floating-point number, also known +as `float16` or `binary16`, as defined by the IEEE 754 standard. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a half-precision floating-point number. Otherwise +`false`. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat16 } from "@nick/is/float16"; + +isFloat16(1); // true +isFloat16(1.5); // true +isFloat16(3.140625); // true +isFloat16(NaN); // false +isFloat16(1.1); // false +isFloat16(Math.PI); // false +isFloat16(Infinity); // false +``` + +## `isFloat16` + +#### Signature + +```ts ignore +function isFloat16(it: unknown): it is Float16; +``` + +Checks if a value is a 16-bit half-precision floating-point number, also known +as `float16` or `binary16`, as defined by the IEEE 754 standard. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a half-precision floating-point number. Otherwise +`false`. + +###### Category + +`Numbers` + +## `isFloat16` + +#### Signature + +```ts ignore +function isFloat16(it: any): it is Float16; +``` + +## `isFloat32` + +#### Signature + +```ts ignore +function isFloat32(it: N): it is Float32; +``` + +Checks if the value is a floating-point number. Supports single-precision +floating-point numbers. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a single-precision floating-point number, otherwise +`false`. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat32 } from "@nick/is/float32"; + +isFloat32(1); // false +isFloat32(1.0); // false +isFloat32(1.1); // true +isFloat32(1.00001e1); // true +``` + +## `isFloat32` + +#### Signature + +```ts ignore +function isFloat32(it: unknown): it is Float32; +``` + +Checks if the value is a floating-point number. Supports single-precision +floating-point numbers. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a single-precision floating-point number, otherwise +`false`. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat32 } from "@nick/is/float32"; + +isFloat32(1); // false +isFloat32(1.0); // false +isFloat32(1.1); // true +isFloat32(1.00001e1); // true +``` + +## `isFloat64` + +#### Signature + +```ts ignore +function isFloat64(it: N): it is Float64; +``` + +Checks if the value is a float64-precision floating-point number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a float64-precision floating-point number, `false` +otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat64 } from "jsr:@nick/is/float64"; + +console.log(isFloat64(1.5)); // true +console.log(isFloat64(0)); // false +console.log(isFloat64(1)); // false +console.log(isFloat64(-1)); // false +console.log(isFloat64(NaN)); // false +console.log(isFloat64(Infinity)); // false +``` + +## `isFloat64` + +#### Signature + +```ts ignore +function isFloat64(it: unknown): it is Float64; +``` + +Checks if the value is a float64-precision floating-point number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a float64-precision floating-point number, `false` +otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isFloat64 } from "jsr:@nick/is/float64"; + +console.log(isFloat64(1.5)); // true +console.log(isFloat64(0)); // false +console.log(isFloat64(1)); // false +console.log(isFloat64(-1)); // false +console.log(isFloat64(NaN)); // false +console.log(isFloat64(Infinity)); // false +``` + +## `isInfinity` + +#### Signature + +```ts ignore +function isInfinity(it: unknown): it is Infinity; +``` + +Checks if a given value is a non-finite number (`Infinity` or `-Infinity`). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a non-finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInfinity } from "@nick/is/number/infinity"; + +console.log(isInfinity(Infinity)); // true +console.log(isInfinity(-Infinity)); // true +console.log(isInfinity(1)); // false +console.log(isInfinity(-1)); // false +console.log(isInfinity(NaN)); // false +``` + +## `isInt16` + +#### Signature + +```ts ignore +function isInt16(it: unknown): it is Int16; +``` + +Checks if a value is a 16-bit integer (between -32768 and 32767). + +To check for an **unsigned** 16-bit integer (0-65535), use +[isUint16](#isuint16 "Jump to symbol: 'isUint16'"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/number"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -32769; // <- TS2322 Type '-32769' is not assignable to type 'Int16'. +``` + +## `isInt16` + +#### Signature + +```ts ignore +function isInt16(it: unknown): it is Int16; +``` + +Checks if a value is a 16-bit integer (between -32768 and 32767). + +To check for an **unsigned** 16-bit integer (0-65535), use +[isUint16](#isuint16 "Jump to symbol: 'isUint16'"). + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInt16 } from "@nick/is/number"; + +isInt16(32768); // false +isInt16(-32769); // false +isInt16(1); // true +isInt16(32767); // true +isInt16(-32768); // true +``` + +## `isInt32` + +#### Signature + +```ts ignore +function isInt32(it: N): it is Int32; +``` + +Checks if a given value is a signed 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a signed 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`int32` `number` + +#### Examples + +```ts +import { type Int32, isInt32, type MaybeInt32 } from "jsr:@type/number/int32"; + +let value = 1 as Int32; + +const setValue = (newValue: MaybeInt32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -2147483649; // <- TS2322 Type '-2147483649' is not assignable to type 'Int32'. +``` + +## `isInt32` + +#### Signature + +```ts ignore +function isInt32(it: unknown): it is Int32; +``` + +Checks if a given value is a signed 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is a signed 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`int32` `number` + +#### Examples + +```ts +import { isInt32 } from "jsr:@type/number/int32"; + +console.log(isInt32(0x7FFFFFFF)); // <- true +console.log(isInt32(-2147483649)); // <- false +``` + +## `isInt8` + +#### Signature + +```ts ignore +function isInt8(it: N): it is Int8; +``` + +Checks if a given value is a signed 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a signed 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInt8 } from "@nick/is/int8"; + +isInt8(1); // true +isInt8(1.0); // false +isInt8(1.1); // false +isInt8(1.00001e1); // false +``` + +## `isInt8` + +#### Signature + +```ts ignore +function isInt8(it: unknown): it is Int8; +``` + +Checks if a given value is a signed 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a signed 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInt8 } from "@nick/is/int8"; + +console.log(isInt8(1)); // true +console.log(isInt8(1.0)); // false +console.log(isInt8(1.1)); // false +console.log(isInt8(1.00001e1)); // false +``` + +## `isInteger` + +#### Signature + +```ts ignore +function isInteger(it: N): it is Integer; +``` + +Checks if a given value is an integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInteger } from "jsr:@nick/is/integer"; + +console.log(isInteger(0)); // true +console.log(isInteger(1)); // true +console.log(isInteger(-1)); // true +console.log(isInteger(1.5)); // false +console.log(isInteger(NaN)); // false +console.log(isInteger(Infinity)); // false +``` + +## `isInteger` + +#### Signature + +```ts ignore +function isInteger(it: unknown): it is Integer; +``` + +Checks if a given value is an integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isInteger } from "jsr:@nick/is/integer"; + +console.log(isInteger(0)); // true +console.log(isInteger(1)); // true +console.log(isInteger(-1)); // true +console.log(isInteger(1.5)); // false +console.log(isInteger(NaN)); // false +console.log(isInteger(Infinity)); // false +``` + +## `isNaN` + +#### Signature + +```ts ignore +function isNaN(it: N): it is NaN; +``` + +Checks if a given value is `NaN` (not a number). This is a type-safe alias of +the global `isNaN` function, + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `NaN`, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNaN } from "jsr:@type/number"; + +console.log(isNaN(0)); // false +console.log(isNaN(1)); // false +console.log(isNaN(1.5)); // false +console.log(isNaN(NaN)); // true +console.log(isNaN(Infinity)); // false +``` + +## `isNaN` + +#### Signature + +```ts ignore +function isNaN(it: unknown): it is NaN; +``` + +Checks if a given value is `NaN` (not a number). This is a type-safe alias of +the global `isNaN` function, + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `NaN`, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNaN } from "jsr:@type/number"; + +console.log(isNaN(0)); // false +console.log(isNaN(1)); // false +console.log(isNaN(1.5)); // false +console.log(isNaN(NaN)); // true +console.log(isNaN(Infinity)); // false +``` + +## `isNegative` + +#### Signature + +```ts ignore +function isNegative(it: N): it is Negative; +``` + +Checks if a given value is a negative number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`negative` + +#### Examples + +```ts +import { isNegative } from "jsr:@nick/is/integer"; + +console.log(isNegative(0)); // false +console.log(isNegative(1)); // false +console.log(isNegative(1.5)); // false +console.log(isNegative(NaN)); // false +console.log(isNegative(Infinity)); // false + +console.log(isNegative(-0)); // true +console.log(isNegative(-1)); // true +console.log(isNegative(-Infinity)); // true +``` + +## `isNegative` + +#### Signature + +```ts ignore +function isNegative(it: unknown): it is Negative; +``` + +Checks if a given value is a negative number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`negative` + +#### Examples + +```ts +import { isNegative } from "jsr:@nick/is/integer"; + +console.log(isNegative(0)); // false +console.log(isNegative(1)); // false +console.log(isNegative(1.5)); // false +console.log(isNegative(NaN)); // false +console.log(isNegative(Infinity)); // false + +console.log(isNegative(-0)); // true +console.log(isNegative(-1)); // true +console.log(isNegative(-Infinity)); // true +``` + +## `isNegativeFiniteInteger` + +#### Signature + +```ts ignore +function isNegativeFiniteInteger( + it: N, +): it is NegativeFiniteInteger; +``` + +Checks if a given value is a negative finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteInteger(0)); // false +console.log(isNegativeFiniteInteger(1)); // false +console.log(isNegativeFiniteInteger(-1)); // true +console.log(isNegativeFiniteInteger(1.5)); // false +console.log(isNegativeFiniteInteger(NaN)); // false +console.log(isNegativeFiniteInteger(Infinity)); // false +``` + +## `isNegativeFiniteInteger` + +#### Signature + +```ts ignore +function isNegativeFiniteInteger(it: unknown): it is NegativeFiniteInteger; +``` + +Checks if a given value is a negative finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteInteger(0)); // false +console.log(isNegativeFiniteInteger(1)); // false +console.log(isNegativeFiniteInteger(-1)); // true +console.log(isNegativeFiniteInteger(1.5)); // false +console.log(isNegativeFiniteInteger(NaN)); // false +console.log(isNegativeFiniteInteger(Infinity)); // false +``` + +## `isNegativeFiniteNumber` + +#### Signature + +```ts ignore +function isNegativeFiniteNumber(it: N): it is NegativeFinite; +``` + +Checks if a given value is a negative finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteNumber(0)); // false +console.log(isNegativeFiniteNumber(1)); // false +console.log(isNegativeFiniteNumber(-1)); // true +console.log(isNegativeFiniteNumber(1.5)); // false +console.log(isNegativeFiniteNumber(NaN)); // false +console.log(isNegativeFiniteNumber(Infinity)); // false +``` + +## `isNegativeFiniteNumber` + +#### Signature + +```ts ignore +function isNegativeFiniteNumber(it: unknown): it is NegativeFinite; +``` + +Checks if a given value is a negative finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteNumber(0)); // false +console.log(isNegativeFiniteNumber(1)); // false +console.log(isNegativeFiniteNumber(-1)); // true +console.log(isNegativeFiniteNumber(1.5)); // false +console.log(isNegativeFiniteNumber(NaN)); // false +console.log(isNegativeFiniteNumber(Infinity)); // false +``` + +## `isNegativeInfinity` + +#### Signature + +```ts ignore +function isNegativeInfinity(it: unknown): it is NegativeInfinity; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is negative infinity, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `negative` `infinity` + +#### Examples + +```ts +import { isNegativeInfinity } from "@nick/is/number/infinity"; + +console.log(isNegativeInfinity(Infinity)); // false +console.log(isNegativeInfinity(-Infinity)); // true +console.log(isNegativeInfinity(1)); // false +console.log(isNegativeInfinity(-1)); // false +console.log(isNegativeInfinity(NaN)); // false +``` + +## `isNegativeInteger` + +#### Signature + +```ts ignore +function isNegativeInteger(it: N): it is NegativeInteger; +``` + +Checks if a given value is a negative integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeInteger(0)); // false +console.log(isNegativeInteger(1)); // false +console.log(isNegativeInteger(-1)); // true +console.log(isNegativeInteger(1.5)); // false +console.log(isNegativeInteger(NaN)); // false +console.log(isNegativeInteger(Infinity)); // false +``` + +## `isNegativeInteger` + +#### Signature + +```ts ignore +function isNegativeInteger(it: unknown): it is NegativeInteger; +``` + +Checks if a given value is a negative integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeInteger(0)); // false +console.log(isNegativeInteger(1)); // false +console.log(isNegativeInteger(-1)); // true +console.log(isNegativeInteger(1.5)); // false +console.log(isNegativeInteger(NaN)); // false +console.log(isNegativeInteger(Infinity)); // false +``` + +## `isNegativeNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isNegativeNonZeroFiniteInteger( + it: N, +): it is NegativeNonZeroFiniteInteger; +``` + +Checks if a given value is a negative nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteInteger(0)); // false +console.log(isNegativeNonZeroFiniteInteger(1)); // false +console.log(isNegativeNonZeroFiniteInteger(-1)); // true +console.log(isNegativeNonZeroFiniteInteger(1.5)); // false +console.log(isNegativeNonZeroFiniteInteger(NaN)); // false +console.log(isNegativeNonZeroFiniteInteger(Infinity)); // false +``` + +## `isNegativeNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isNegativeNonZeroFiniteInteger( + it: unknown, +): it is NegativeNonZeroFiniteInteger; +``` + +Checks if a given value is a negative nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteInteger(0)); // false +console.log(isNegativeNonZeroFiniteInteger(1)); // false +console.log(isNegativeNonZeroFiniteInteger(-1)); // true +console.log(isNegativeNonZeroFiniteInteger(1.5)); // false +console.log(isNegativeNonZeroFiniteInteger(NaN)); // false +console.log(isNegativeNonZeroFiniteInteger(Infinity)); // false +``` + +## `isNegativeNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isNegativeNonZeroFiniteNumber( + it: N, +): it is NegativeNonZeroFinite; +``` + +Checks if a given value is a negative nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteNumber(0)); // false +console.log(isNegativeNonZeroFiniteNumber(1)); // false +console.log(isNegativeNonZeroFiniteNumber(-1)); // true +console.log(isNegativeNonZeroFiniteNumber(1.5)); // false +console.log(isNegativeNonZeroFiniteNumber(NaN)); // false +console.log(isNegativeNonZeroFiniteNumber(Infinity)); // false +``` + +## `isNegativeNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isNegativeNonZeroFiniteNumber( + it: unknown, +): it is NegativeNonZeroFinite; +``` + +Checks if a given value is a negative nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteNumber(0)); // false +console.log(isNegativeNonZeroFiniteNumber(1)); // false +console.log(isNegativeNonZeroFiniteNumber(-1)); // true +console.log(isNegativeNonZeroFiniteNumber(1.5)); // false +console.log(isNegativeNonZeroFiniteNumber(NaN)); // false +console.log(isNegativeNonZeroFiniteNumber(Infinity)); // false +``` + +## `isNegativeNonZeroInteger` + +#### Signature + +```ts ignore +function isNegativeNonZeroInteger( + it: N, +): it is NegativeNonZeroInteger; +``` + +Checks if a given value is a negative nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroInteger(0)); // false +console.log(isNegativeNonZeroInteger(1)); // false +console.log(isNegativeNonZeroInteger(-1)); // true +console.log(isNegativeNonZeroInteger(1.5)); // false +console.log(isNegativeNonZeroInteger(NaN)); // false +console.log(isNegativeNonZeroInteger(Infinity)); // true +``` + +## `isNegativeNonZeroInteger` + +#### Signature + +```ts ignore +function isNegativeNonZeroInteger(it: unknown): it is NegativeNonZeroInteger; +``` + +Checks if a given value is a negative nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroInteger(0)); // false +console.log(isNegativeNonZeroInteger(1)); // false +console.log(isNegativeNonZeroInteger(-1)); // true +console.log(isNegativeNonZeroInteger(1.5)); // false +console.log(isNegativeNonZeroInteger(NaN)); // false +console.log(isNegativeNonZeroInteger(Infinity)); // true +``` + +## `isNegativeNonZeroNumber` + +#### Signature + +```ts ignore +function isNegativeNonZeroNumber(it: N): it is NegativeNonZero; +``` + +Checks if a given value is a negative nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero number, `false` otherwise. + +#### Examples + +```ts +import { isNegativeNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroNumber(0)); // false +console.log(isNegativeNonZeroNumber(1)); // false +console.log(isNegativeNonZeroNumber(-1)); // true +console.log(isNegativeNonZeroNumber(1.5)); // false +console.log(isNegativeNonZeroNumber(NaN)); // false +console.log(isNegativeNonZeroNumber(Infinity)); // false +``` + +## `isNegativeNonZeroNumber` + +#### Signature + +```ts ignore +function isNegativeNonZeroNumber(it: unknown): it is NegativeNonZero; +``` + +Checks if a given value is a negative nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero number, `false` otherwise. + +#### Examples + +```ts +import { isNegativeNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroNumber(0)); // false +console.log(isNegativeNonZeroNumber(1)); // false +console.log(isNegativeNonZeroNumber(-1)); // true +console.log(isNegativeNonZeroNumber(1.5)); // false +console.log(isNegativeNonZeroNumber(NaN)); // false +console.log(isNegativeNonZeroNumber(Infinity)); // false +``` + +## `isNegativeNumber` + +#### Signature + +```ts ignore +function isNegativeNumber(it: N): it is Negative; +``` + +Checks if a given value is a negative number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`negative` + +#### Examples + +```ts +import { isNegative } from "jsr:@nick/is/integer"; + +console.log(isNegative(0)); // false +console.log(isNegative(1)); // false +console.log(isNegative(1.5)); // false +console.log(isNegative(NaN)); // false +console.log(isNegative(Infinity)); // false + +console.log(isNegative(-0)); // true +console.log(isNegative(-1)); // true +console.log(isNegative(-Infinity)); // true +``` + +## `isNegativeNumber` + +#### Signature + +```ts ignore +function isNegativeNumber(it: unknown): it is Negative; +``` + +Checks if a given value is a negative number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`negative` + +#### Examples + +```ts +import { isNegative } from "jsr:@nick/is/integer"; + +console.log(isNegative(0)); // false +console.log(isNegative(1)); // false +console.log(isNegative(1.5)); // false +console.log(isNegative(NaN)); // false +console.log(isNegative(Infinity)); // false + +console.log(isNegative(-0)); // true +console.log(isNegative(-1)); // true +console.log(isNegative(-Infinity)); // true +``` + +## `isNegativeZero` + +#### Signature + +```ts ignore +function isNegativeZero(it: N): it is NegativeZero; +``` + +Checks if a given value is negative zero, which is a special numeric value in +JavaScript, distinctly different from it's positive counterpart. Checking for +negative zero involves more than simply `x === -0`, as `-0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `-0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is negative zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero } from "jsr:@nick/is/number"; + +console.log(isNegativeZero(-0)); // true +console.log(isNegativeZero(0)); // false +console.log(isNegativeZero(-1)); // false +console.log(isNegativeZero(1)); // false +``` + +## `isNegativeZero` + +#### Signature + +```ts ignore +function isNegativeZero(it: unknown): it is NegativeZero; +``` + +Checks if a given value is negative zero, which is a special numeric value in +JavaScript, distinctly different from it's positive counterpart. Checking for +negative zero involves more than simply `x === -0`, as `-0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `-0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is negative zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero } from "jsr:@nick/is/number"; + +console.log(isNegativeZero(-0)); // true +console.log(isNegativeZero(0)); // false +console.log(isNegativeZero(-1)); // false +console.log(isNegativeZero(1)); // false +``` + +## `isNonZero` + +#### Signature + +```ts ignore +function isNonZero(it: N): it is NonZero; +``` + +Checks if a given value is a nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero } from "jsr:@nick/is/number/nonzero"; + +console.log(isNonZero(1)); // true +console.log(isNonZero(-1)); // true +console.log(isNonZero(1.5)); // true + +console.log(isNonZero(0)); // false +console.log(isNonZero(-0)); // false +console.log(isNonZero(NaN)); // false +console.log(isNonZero(Infinity)); // true +``` + +## `isNonZero` + +#### Signature + +```ts ignore +function isNonZero(it: unknown): it is NonZero; +``` + +Checks if a given value is a nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero } from "jsr:@nick/is/number/nonzero"; + +console.log(isNonZero(1)); // true +console.log(isNonZero(-1)); // true +console.log(isNonZero(1.5)); // true + +console.log(isNonZero(0)); // false +console.log(isNonZero(-0)); // false +console.log(isNonZero(NaN)); // false +console.log(isNonZero(Infinity)); // true +``` + +## `isNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isNonZeroFiniteInteger( + it: N, +): it is NonZeroFiniteInteger; +``` + +Checks if a given value is a nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteInteger(0)); // false +console.log(isNonZeroFiniteInteger(1)); // true +console.log(isNonZeroFiniteInteger(-1)); // true +console.log(isNonZeroFiniteInteger(1.5)); // false +console.log(isNonZeroFiniteInteger(NaN)); // false +console.log(isNonZeroFiniteInteger(Infinity)); // true +``` + +## `isNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isNonZeroFiniteInteger(it: unknown): it is NonZeroFiniteInteger; +``` + +Checks if a given value is a nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteInteger(0)); // false +console.log(isNonZeroFiniteInteger(1)); // true +console.log(isNonZeroFiniteInteger(-1)); // true +console.log(isNonZeroFiniteInteger(1.5)); // false +console.log(isNonZeroFiniteInteger(NaN)); // false +console.log(isNonZeroFiniteInteger(Infinity)); // true +``` + +## `isNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isNonZeroFiniteNumber(it: N): it is NonZeroFinite; +``` + +Checks if a given value is a nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteNumber(0)); // false +console.log(isNonZeroFiniteNumber(1)); // true +console.log(isNonZeroFiniteNumber(-1)); // true +console.log(isNonZeroFiniteNumber(1.5)); // true +console.log(isNonZeroFiniteNumber(NaN)); // false +console.log(isNonZeroFiniteNumber(Infinity)); // true +``` + +## `isNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isNonZeroFiniteNumber(it: unknown): it is NonZeroFinite; +``` + +Checks if a given value is a nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteNumber(0)); // false +console.log(isNonZeroFiniteNumber(1)); // true +console.log(isNonZeroFiniteNumber(-1)); // true +console.log(isNonZeroFiniteNumber(1.5)); // true +console.log(isNonZeroFiniteNumber(NaN)); // false +console.log(isNonZeroFiniteNumber(Infinity)); // true +``` + +## `isNonZeroInteger` + +#### Signature + +```ts ignore +function isNonZeroInteger(it: N): it is NonZeroInteger; +``` + +Checks if a given value is a nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroInteger(0)); // false +console.log(isNonZeroInteger(1)); // true +console.log(isNonZeroInteger(-1)); // true +console.log(isNonZeroInteger(1.5)); // false +console.log(isNonZeroInteger(NaN)); // false +console.log(isNonZeroInteger(Infinity)); // true +``` + +## `isNonZeroInteger` + +#### Signature + +```ts ignore +function isNonZeroInteger(it: unknown): it is NonZeroInteger; +``` + +Checks if a given value is a nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroInteger(0)); // false +console.log(isNonZeroInteger(1)); // true +console.log(isNonZeroInteger(-1)); // true +console.log(isNonZeroInteger(1.5)); // false +console.log(isNonZeroInteger(NaN)); // false +console.log(isNonZeroInteger(Infinity)); // true +``` + +## `isNonZeroNumber` + +#### Signature + +```ts ignore +function isNonZeroNumber(it: N): it is NonZero; +``` + +Checks if a given value is a nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero } from "jsr:@nick/is/number/nonzero"; + +console.log(isNonZero(1)); // true +console.log(isNonZero(-1)); // true +console.log(isNonZero(1.5)); // true + +console.log(isNonZero(0)); // false +console.log(isNonZero(-0)); // false +console.log(isNonZero(NaN)); // false +console.log(isNonZero(Infinity)); // true +``` + +## `isNonZeroNumber` + +#### Signature + +```ts ignore +function isNonZeroNumber(it: unknown): it is NonZero; +``` + +Checks if a given value is a nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero } from "jsr:@nick/is/number/nonzero"; + +console.log(isNonZero(1)); // true +console.log(isNonZero(-1)); // true +console.log(isNonZero(1.5)); // true + +console.log(isNonZero(0)); // false +console.log(isNonZero(-0)); // false +console.log(isNonZero(NaN)); // false +console.log(isNonZero(Infinity)); // true +``` + +## `isNumber` + +#### Signature + +```ts ignore +function isNumber(it: unknown): it is number; +``` + +Checks if the given value is a number. This includes all numbers, without +distinguishing between `NaN`, `Infinity`, and other special values. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a number, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isNumber } from "jsr:@nick/is/number"; + +isNumber("123"); // false +isNumber(123); // true +``` + +```ts +import { isNumber } from "jsr:@nick/is/number"; + +const x: unknown = 123; +if (isNumber(x)) { + console.log(x + 1); + // ^? const x: number +} +``` + +## `isOdd` + +#### Signature + +```ts ignore +function isOdd(it: T): it is Odd; +``` + +Checks if a given number / bigint is odd. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :----------------------------------------------------------------- | +| **`it`** | The number or bigint to check, either literal or in string format. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOdd` + +#### Signature + +```ts ignore +function isOdd(it: number | `${number}`): it is Odd; +``` + +Checks if a given number / numeric string is odd. Returns `true` if the value is +not divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------- | +| **`it`** | The number or numeric string to check. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOdd` + +#### Signature + +```ts ignore +function isOdd(it: bigint | `${bigint}`): it is Odd; +``` + +Checks if a given bigint or bigint string is an odd number. Returns `true` if +the value is not divisible by `2`, and `false` otherwise. This usually +corresponds to integers that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------ | +| **`it`** | The bigint or bigint string to check. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOdd` + +#### Signature + +```ts ignore +function isOdd(it: unknown): it is Odd; +``` + +Checks if a given number / bigint is odd. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an odd finite integer, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOddNumber` + +#### Signature + +```ts ignore +function isOddNumber(it: T): it is Odd; +``` + +Checks if a given number / bigint is odd. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :----------------------------------------------------------------- | +| **`it`** | The number or bigint to check, either literal or in string format. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOddNumber` + +#### Signature + +```ts ignore +function isOddNumber(it: number | `${number}`): it is Odd; +``` + +Checks if a given number / numeric string is odd. Returns `true` if the value is +not divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------- | +| **`it`** | The number or numeric string to check. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOddNumber` + +#### Signature + +```ts ignore +function isOddNumber(it: bigint | `${bigint}`): it is Odd; +``` + +Checks if a given bigint or bigint string is an odd number. Returns `true` if +the value is not divisible by `2`, and `false` otherwise. This usually +corresponds to integers that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------ | +| **`it`** | The bigint or bigint string to check. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOddNumber` + +#### Signature + +```ts ignore +function isOddNumber(it: unknown): it is Odd; +``` + +Checks if a given number / bigint is odd. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an odd finite integer, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isPositive` + +#### Signature + +```ts ignore +function isPositive(it: N): it is Positive; +``` + +Checks if a given value is a positive number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive } from "jsr:@nick/is/integer"; + +console.log(isPositive(0)); // true +console.log(isPositive(1)); // true +console.log(isPositive(-1)); // false +console.log(isPositive(1.5)); // true +console.log(isPositive(NaN)); // false +console.log(isPositive(Infinity)); // true +``` + +## `isPositive` + +#### Signature + +```ts ignore +function isPositive(it: unknown): it is Positive; +``` + +Checks if a given value is a positive number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive } from "jsr:@nick/is/integer"; + +console.log(isPositive(0)); // true +console.log(isPositive(1)); // true +console.log(isPositive(-1)); // false +console.log(isPositive(1.5)); // true +console.log(isPositive(NaN)); // false +console.log(isPositive(Infinity)); // true +``` + +## `isPositiveFiniteInteger` + +#### Signature + +```ts ignore +function isPositiveFiniteInteger( + it: N, +): it is PositiveFiniteInteger; +``` + +Checks if a given value is a positive finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteInteger(0)); // false +console.log(isPositiveFiniteInteger(1)); // true +console.log(isPositiveFiniteInteger(-1)); // false +console.log(isPositiveFiniteInteger(1.5)); // false +console.log(isPositiveFiniteInteger(NaN)); // false +console.log(isPositiveFiniteInteger(Infinity)); // false +``` + +## `isPositiveFiniteInteger` + +#### Signature + +```ts ignore +function isPositiveFiniteInteger(it: unknown): it is PositiveFiniteInteger; +``` + +Checks if a given value is a positive finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteInteger(0)); // false +console.log(isPositiveFiniteInteger(1)); // true +console.log(isPositiveFiniteInteger(-1)); // false +console.log(isPositiveFiniteInteger(1.5)); // false +console.log(isPositiveFiniteInteger(NaN)); // false +console.log(isPositiveFiniteInteger(Infinity)); // false +``` + +## `isPositiveFiniteNumber` + +#### Signature + +```ts ignore +function isPositiveFiniteNumber(it: N): it is PositiveFinite; +``` + +Checks if a given value is a positive finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteNumber(0)); // false +console.log(isPositiveFiniteNumber(1)); // true +console.log(isPositiveFiniteNumber(-1)); // false +console.log(isPositiveFiniteNumber(1.5)); // true +console.log(isPositiveFiniteNumber(NaN)); // false +console.log(isPositiveFiniteNumber(Infinity)); // false +``` + +## `isPositiveFiniteNumber` + +#### Signature + +```ts ignore +function isPositiveFiniteNumber(it: unknown): it is PositiveFinite; +``` + +Checks if a given value is a positive finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteNumber(0)); // false +console.log(isPositiveFiniteNumber(1)); // true +console.log(isPositiveFiniteNumber(-1)); // false +console.log(isPositiveFiniteNumber(1.5)); // true +console.log(isPositiveFiniteNumber(NaN)); // false +console.log(isPositiveFiniteNumber(Infinity)); // false +``` + +## `isPositiveInfinity` + +#### Signature + +```ts ignore +function isPositiveInfinity(it: unknown): it is PositiveInfinity; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is positive infinity, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `positive` `infinity` + +#### Examples + +```ts +import { isPositiveInfinity } from "@nick/is/number/infinity"; + +console.log(isPositiveInfinity(Infinity)); // false +console.log(isPositiveInfinity(-Infinity)); // true +console.log(isPositiveInfinity(1)); // false +console.log(isPositiveInfinity(-1)); // false +console.log(isPositiveInfinity(NaN)); // false +``` + +## `isPositiveInteger` + +#### Signature + +```ts ignore +function isPositiveInteger(it: N): it is PositiveInteger; +``` + +Checks if a given value is a positive integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveInteger(0)); // true +console.log(isPositiveInteger(1)); // true +console.log(isPositiveInteger(-1)); // false +console.log(isPositiveInteger(1.5)); // false +console.log(isPositiveInteger(NaN)); // false +console.log(isPositiveInteger(Infinity)); // false +``` + +## `isPositiveInteger` + +#### Signature + +```ts ignore +function isPositiveInteger(it: unknown): it is PositiveInteger; +``` + +Checks if a given value is a positive integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveInteger(0)); // true +console.log(isPositiveInteger(1)); // true +console.log(isPositiveInteger(-1)); // false +console.log(isPositiveInteger(1.5)); // false +console.log(isPositiveInteger(NaN)); // false +console.log(isPositiveInteger(Infinity)); // false +``` + +## `isPositiveNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isPositiveNonZeroFiniteInteger( + it: N, +): it is PositiveNonZeroFiniteInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteInteger(0)); // false +console.log(isPositiveNonZeroFiniteInteger(1)); // true +console.log(isPositiveNonZeroFiniteInteger(-1)); // false +console.log(isPositiveNonZeroFiniteInteger(1.5)); // false +console.log(isPositiveNonZeroFiniteInteger(NaN)); // false +console.log(isPositiveNonZeroFiniteInteger(Infinity)); // true +``` + +## `isPositiveNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isPositiveNonZeroFiniteInteger( + it: unknown, +): it is PositiveNonZeroFiniteInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteInteger(0)); // false +console.log(isPositiveNonZeroFiniteInteger(1)); // true +console.log(isPositiveNonZeroFiniteInteger(-1)); // false +console.log(isPositiveNonZeroFiniteInteger(1.5)); // false +console.log(isPositiveNonZeroFiniteInteger(NaN)); // false +console.log(isPositiveNonZeroFiniteInteger(Infinity)); // true +``` + +## `isPositiveNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroFiniteNumber( + it: N, +): it is PositiveNonZeroFinite; +``` + +Checks if a given value is a positive nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteNumber(0)); // false +console.log(isPositiveNonZeroFiniteNumber(1)); // true +console.log(isPositiveNonZeroFiniteNumber(-1)); // false +console.log(isPositiveNonZeroFiniteNumber(1.5)); // true +console.log(isPositiveNonZeroFiniteNumber(NaN)); // false +console.log(isPositiveNonZeroFiniteNumber(Infinity)); // true +``` + +## `isPositiveNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroFiniteNumber( + it: unknown, +): it is PositiveNonZeroFinite; +``` + +Checks if a given value is a positive nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteNumber(0)); // false +console.log(isPositiveNonZeroFiniteNumber(1)); // true +console.log(isPositiveNonZeroFiniteNumber(-1)); // false +console.log(isPositiveNonZeroFiniteNumber(1.5)); // true +console.log(isPositiveNonZeroFiniteNumber(NaN)); // false +console.log(isPositiveNonZeroFiniteNumber(Infinity)); // true +``` + +## `isPositiveNonZeroInteger` + +#### Signature + +```ts ignore +function isPositiveNonZeroInteger( + it: N, +): it is PositiveNonZeroInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroInteger(0)); // false +console.log(isPositiveNonZeroInteger(1)); // true +console.log(isPositiveNonZeroInteger(-1)); // false +console.log(isPositiveNonZeroInteger(1.5)); // false +console.log(isPositiveNonZeroInteger(NaN)); // false +console.log(isPositiveNonZeroInteger(Infinity)); // true +``` + +## `isPositiveNonZeroInteger` + +#### Signature + +```ts ignore +function isPositiveNonZeroInteger(it: unknown): it is PositiveNonZeroInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroInteger(0)); // false +console.log(isPositiveNonZeroInteger(1)); // true +console.log(isPositiveNonZeroInteger(-1)); // false +console.log(isPositiveNonZeroInteger(1.5)); // false +console.log(isPositiveNonZeroInteger(NaN)); // false +console.log(isPositiveNonZeroInteger(Infinity)); // true +``` + +## `isPositiveNonZeroNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroNumber(it: N): it is PositiveNonZero; +``` + +Checks if a given value is a positive nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroNumber(0)); // false +console.log(isPositiveNonZeroNumber(1)); // true +console.log(isPositiveNonZeroNumber(-1)); // false +console.log(isPositiveNonZeroNumber(1.5)); // true +console.log(isPositiveNonZeroNumber(NaN)); // false +console.log(isPositiveNonZeroNumber(Infinity)); // true +``` + +## `isPositiveNonZeroNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroNumber(it: unknown): it is PositiveNonZero; +``` + +Checks if a given value is a positive nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroNumber(0)); // false +console.log(isPositiveNonZeroNumber(1)); // true +console.log(isPositiveNonZeroNumber(-1)); // false +console.log(isPositiveNonZeroNumber(1.5)); // true +console.log(isPositiveNonZeroNumber(NaN)); // false +console.log(isPositiveNonZeroNumber(Infinity)); // true +``` + +## `isPositiveNonZeroNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroNumber(it: unknown): it is PositiveNonZero; +``` + +## `isPositiveNumber` + +#### Signature + +```ts ignore +function isPositiveNumber(it: N): it is Positive; +``` + +Checks if a given value is a positive number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive } from "jsr:@nick/is/integer"; + +console.log(isPositive(0)); // true +console.log(isPositive(1)); // true +console.log(isPositive(-1)); // false +console.log(isPositive(1.5)); // true +console.log(isPositive(NaN)); // false +console.log(isPositive(Infinity)); // true +``` + +## `isPositiveNumber` + +#### Signature + +```ts ignore +function isPositiveNumber(it: unknown): it is Positive; +``` + +Checks if a given value is a positive number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive } from "jsr:@nick/is/integer"; + +console.log(isPositive(0)); // true +console.log(isPositive(1)); // true +console.log(isPositive(-1)); // false +console.log(isPositive(1.5)); // true +console.log(isPositive(NaN)); // false +console.log(isPositive(Infinity)); // true +``` + +## `isPositiveZero` + +#### Signature + +```ts ignore +function isPositiveZero(it: N): it is PositiveZero; +``` + +Checks if a given value is positive zero, which is a special numeric value in +JavaScript, distinctly different from it's negative counterpart. Checking for +positive zero involves more than simply `x === +0`, as `+0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `+0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is positive zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero } from "jsr:@nick/is/number"; + +console.log(isPositiveZero(-0)); // false +console.log(isPositiveZero(0)); // true +console.log(isPositiveZero(-1)); // false +console.log(isPositiveZero(1)); // false +``` + +## `isPositiveZero` + +#### Signature + +```ts ignore +function isPositiveZero(it: unknown): it is PositiveZero; +``` + +Checks if a given value is positive zero, which is a special numeric value in +JavaScript, distinctly different from it's negative counterpart. Checking for +positive zero involves more than simply `x === +0`, as `+0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `+0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is positive zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero } from "jsr:@nick/is/number"; + +console.log(isPositiveZero(-0)); // false +console.log(isPositiveZero(0)); // true +console.log(isPositiveZero(-1)); // false +console.log(isPositiveZero(1)); // false +``` + +## `isUint16` + +#### Signature + +```ts ignore +function isUint16(it: N): it is Uint16; +``` + +Checks if a given value is an unsigned 16-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `isUint16` + +#### Signature + +```ts ignore +function isUint16(it: unknown): it is Uint16; +``` + +Checks if a given value is an unsigned 16-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `isUint32` + +#### Signature + +```ts ignore +function isUint32(it: N): it is Uint32; +``` + +Checks if a given value is an unsigned 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `isUint32` + +#### Signature + +```ts ignore +function isUint32(it: unknown): it is Uint32; +``` + +Checks if a given value is an unsigned 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `isUint8` + +#### Signature + +```ts ignore +function isUint8(it: N): it is Uint8; +``` + +Checks if a given value is an unsigned 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint8 } from "jsr:@nick/is/uint8"; + +isUint8(1); // true +isUint8(128); // true +isUint8(0xFF); // true +isUint8(-1); // false +isUint8(420); // false +``` + +## `isUint8` + +#### Signature + +```ts ignore +function isUint8(it: unknown): it is Uint8; +``` + +Checks if a given value is an unsigned 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint8 } from "jsr:@nick/is/uint8"; + +isUint8(1); // true +isUint8(128); // true +isUint8(0xFF); // true +isUint8(-1); // false +isUint8(420); // false +``` + +## `isZero` + +#### Signature + +```ts ignore +function isZero(it: N): it is Zero; +``` + +Checks if a given value is a zero number. This includes both positive and +negative zero. It also supports numbers and numeric strings. + +- To check exclusively for `-0`, use + [isNegativeZero](#isnegativezero "Jump to symbol: 'isNegativeZero'") instead. +- To check exclusively for `+0` (meaning zero, but **not** negative zero), use + [isPositiveZero](#ispositivezero "Jump to symbol: 'isPositiveZero'") instead. + +###### Category + +`Numbers` + +## `isZero` + +#### Signature + +```ts ignore +function isZero(it: unknown): it is Zero; +``` + +Checks if a given value is a zero number. This includes both positive and +negative zero. It also supports numbers and numeric strings. + +- To check exclusively for `-0`, use + [isNegativeZero](#isnegativezero "Jump to symbol: 'isNegativeZero'") instead. +- To check exclusively for `+0` (meaning zero, but **not** negative zero), use + [isPositiveZero](#ispositivezero "Jump to symbol: 'isPositiveZero'") instead. + +###### Category + +`Numbers` + +## `AnyRange` + +#### Signature + +```ts ignore +export type AnyRange = + | RangeInclusiveMin + | RangeInclusive + | RangeInclusiveMax + | RangeExclusive; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `BigInteger` + +#### Signature + +```ts ignore +export type BigInteger = CastInt; +``` + +Casts a value into a big integer type (which is really just a bigint). If the +value is not a bigint or a string containing a valid integer, it will resolve to +`never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `Cast` + +#### Signature + +```ts ignore +export type Cast = Extract & T; +``` + +Casts a value into a specific numeric type. If the value is not a number, it +will resolve to `never`, indicating its incompatibility with the type. + +This is a low-level utility type that primarily serves as an internal helper for +more user-friendly types like [Integer](#integer "Jump to symbol: 'Integer'") +and [Positive](#positive "Jump to symbol: 'Positive'"). Unless you're building +custom numeric types with your own branding, you most likely never directly +handle this type in the wild. + +##### Type Parameters + +- **`N`** +- **`T`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { Cast } from "jsr:@nick/is/number"; + +declare const MY_DOUBLE: unique symbol; +type DOUBLE = Cast; + +let x = 4.3210123210 as DOUBLE; +let y = 3.1415926535 as DOUBLE; + +console.log(x + y); // 7.4626049745 + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'DOUBLE'. +``` + +## `CastInt` + +#### Signature + +```ts ignore +export type CastInt = Extract & T; +``` + +Casts a value into a specific integer type. If the value is not a bigint, it +will resolve to `never`, indicating its incompatibility with the type. + +This is a low-level utility type that primarily serves as an internal helper for +more user-friendly types like +[BigInteger](#biginteger "Jump to symbol: 'BigInteger'") or +[PositiveBigInteger](#positivebiginteger "Jump to symbol: 'PositiveBigInteger'"). +Unless you're building custom numeric types with your own branding, you most +likely will never directly handle this type in the wild. + +##### Type Parameters + +- **`N`** +- **`T`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { CastInt } from "jsr:@nick/is/number"; + +declare const INTEGER: unique symbol; +type INTEGER = CastInt; + +let x = 3n as INTEGER; +let y = 5n as INTEGER; + +console.log(x + y); // 8n +``` + +## `Derange` + +#### Signature + +```ts ignore +export type Derange = + | readonly [number, number, "[]"] + | readonly [number, "[]"] + | readonly [number, number, "[)"] + | readonly [number, "[)"] + | readonly [number, number, "(]"] + | readonly [number, "(]"] + | readonly [number, number, "()"] + | readonly [number, "()"] + | readonly [number, number, Exclusivity] + | readonly [number, Exclusivity]; +``` + +## `Even` + +#### Signature + +```ts ignore +export type Even = Cast; +``` + +Branded type representing an even number or bigint. Used by overloads of the +[`isEven`](#iseven "Jump to symbol: 'isEven'") function to differentiate between +odd and even numbers. + +##### Type Parameters + +- **`T`** extends `Numeric` (default: `Numeric`) + +--- + +###### Category + +`Numeric` + +## `Exclusivity` + +#### Signature + +```ts ignore +export type Exclusivity = AnyRange[2]; +``` + +## `Finite` + +#### Signature + +```ts ignore +export type Finite = Cast; +``` + +Casts a value into a finite type. If the value is not a number, it will resolve +to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `FiniteInteger` + +#### Signature + +```ts ignore +export type FiniteInteger = Cast; +``` + +Casts a value into a finite integer type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `Float` + +#### Signature + +```ts ignore +export type Float = Cast; +``` + +Casts a value into a floating-point type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float` `number` + +#### Examples + +```ts +import { type Float, isFloat } from "@nick/is/float"; + +let x = 1.5 as Float, y = 0; + +if (isFloat(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float'. +``` + +## `Float16` + +#### Signature + +```ts ignore +export type Float16 = Cast; +``` + +Casts a value into a 16-bit floating-point type (half-precision). + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float16` `number` + +#### Examples + +```ts +import { type Float16, isFloat16 } from "@nick/is/float16"; + +let i = 1.5 as Float16, y = 0; + +if (isFloat16(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = 1; // <- TS2322 Type '1' is not assignable to type 'Float16'. +``` + +## `Float32` + +#### Signature + +```ts ignore +export type Float32 = Cast; +``` + +Casts a value into a floating-point type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float32` `number` + +#### Examples + +```ts +import { type Float32, isFloat32 } from "@nick/is/float32"; + +let x = 1.5 as Float32, y = 0; + +if (isFloat32(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float32'. +``` + +## `Float64` + +#### Signature + +```ts ignore +export type Float64 = Cast; +``` + +Casts a value into a float64-precision floating-point type. If the value is not +a number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`float64` `number` + +#### Examples + +```ts +import { type Float64, isFloat64 } from "jsr:@type/number/float64"; + +let x = 1.5 as Float64, y = 0; + +if (isFloat64(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Float64'. +``` + +## `Infinity` + +#### Signature + +```ts ignore +export type Infinity = PositiveInfinity | NegativeInfinity; +``` + +Special type representing either positive or negative infinity. + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` + +## `InRange` + +#### Signature + +```ts ignore +export type InRange< + N extends number, + Min extends number = number, + Max extends number = number, + Tex extends Exclusivity = Exclusivity, +> = + & (number extends N ? IsInRange + : `${Min}|${Max}` extends `-${number}|-${number}` + ? `${N}` extends `-${number}` ? IsInRange : never + : `${Min}|${Max}` extends `${number}|-${number}` ? never + : `${Min}|${Max}` extends `-${number}|${number}` + ? `${N}` extends `-${number}` ? IsInRange : never + : `${N}` extends `-${number}` ? never + : IsInRange) + & N; +``` + +Type-level equivalent to the [`inRange`](#inrange "Jump to symbol: 'inRange'") +function, which (naively) checks if a number is within a given range. The range +can be specified in multiple ways, with one of four different exclusivity types. + +##### Type Parameters + +- **`N`** extends `number` +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `Exclusivity`) + +--- + +###### See Also + +- [`inRange`](#inrange "Jump to symbol: 'inRange'") for more information. + +## `Int16` + +#### Signature + +```ts ignore +export type Int16 = Cast; +``` + +Casts a value into a signed 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/int16"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -32769; // <- TS2322 Type '-32769' is not assignable to type 'Int16'. +``` + +## `Int32` + +#### Signature + +```ts ignore +export type Int32 = Cast; +``` + +Casts a value into a signed 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int32` `number` + +#### Examples + +```ts +import { type Int32, isInt32 } from "jsr:@type/number/int32"; + +let value = 1 as Int32; + +const setValue = (newValue: Int32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -2147483649; // <- TS2322 Type '-2147483649' is not assignable to type 'Int32'. +``` + +## `Int8` + +#### Signature + +```ts ignore +export type Int8 = Cast; +``` + +Casts a value into a signed 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`int8` `number` + +#### Examples + +```ts +import { type Int8, isInt8 } from "@nick/is/int8"; + +let i = 1 as Int8, y = 0; + +if (isInt8(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = 1.5; // <- TS2322 Type '1.5' is not assignable to type 'Int8'. +``` + +## `Integer` + +#### Signature + +```ts ignore +export type Integer = N extends bigint + ? `${N}` extends `${infer I extends number}` ? N & Integer : never + : N extends number ? number extends N ? N & INTEGER + : `${N}` extends `${bigint}` ? N & INTEGER + : never + : never; +``` + +Casts a value into an integer type. If the value is not an number, or is a +non-integral number like 3.14, it will resolve to `never`. + +**Note**: once a value is cast to a type with this narrow of a constraint, +TypeScript's compiler will refuse any assignment to it that is not _exactly_ +compatible with the type. If you find yourself encountering errors about +incompatible types, try using the +[MaybeInteger](#maybeinteger "Jump to symbol: 'MaybeInteger'") type instead. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { type Integer, isInteger } from "jsr:@type/number"; + +function add(a: Integer, b: Integer) { + return (a + b) as Integer; +} + +let x = 1 as Integer, y = 2 as Integer, z = 3; + +if (isInteger(z)) { + console.log(add(add(x, y), z)); +} else { + console.log(add(x, y)); +} + +// These will raise TypeScript compiler errors: +add(x, z); +add(y, 3); + +// This level of strictness can be a bit silly in the wrong application: +x = 1; // <- TS4321 (`MaybeInteger` would be a better choice here) +``` + +## `IsEven` + +#### Signature + +```ts ignore +export type IsEven = `${T}` extends + `${"" | bigint}${1 | 3 | 5 | 7 | 9}` ? True : False; +``` + +Type-level equivalent of [`isEven`](#iseven "Jump to symbol: 'isEven'"), which +checks if a given numeric type (number or bigint) ends in an even number. +Returns [True](#true "Jump to symbol: 'True'") if so, and +[False](#false "Jump to symbol: 'False'") otherwise. + +##### Type Parameters + +- **`T`** extends `Numeric` +- **`True`** (default: `T`) +- **`False`** (default: `never`) + +--- + +###### Category + +`Numeric` + +## `IsOdd` + +#### Signature + +```ts ignore +export type IsOdd = + `${number}` extends `${T}` ? True + : `${bigint}` extends `${T}` ? True + : `${T}` extends `${infer _}${1 | 3 | 5 | 7 | 9}` ? True + : False; +``` + +Type-level equivalent of [`isOdd`](#isodd "Jump to symbol: 'isOdd'"), which +checks if a given numeric type (number or bigint) ends in an odd number. Returns +[True](#true "Jump to symbol: 'True'") if so, and +[False](#false "Jump to symbol: 'False'") otherwise. + +##### Type Parameters + +- **`T`** extends `Numeric` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Numeric` + +## `MaybeFinite` + +#### Signature + +```ts ignore +export type MaybeFinite = Cast; +``` + +Casts a value into a partial finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeFloat` + +#### Signature + +```ts ignore +export type MaybeFloat = Cast; +``` + +Casts a value into a partial floating-point type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float` `number` + +#### Examples + +```ts +import { isFloat, type MaybeFloat } from "@nick/is/float"; + +let x = 1.5 as MaybeFloat, y = 0; + +if (isFloat(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Float`) +``` + +## `MaybeFloat16` + +#### Signature + +```ts ignore +export type MaybeFloat16 = Cast; +``` + +Casts a value into a partial 16-bit floating-point type (half-precision). + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float16` `number` + +## `MaybeFloat32` + +#### Signature + +```ts ignore +export type MaybeFloat32 = Cast; +``` + +Casts a value into a partial floating-point type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float32` `number` + +#### Examples + +```ts +import { isFloat32, type MaybeFloat32 } from "@nick/is/float32"; + +let x = 1.5 as MaybeFloat32, y = 0; + +if (isFloat32(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Float32`) +``` + +## `MaybeFloat64` + +#### Signature + +```ts ignore +export type MaybeFloat64 = Cast; +``` + +Casts a value into a partial float64-precision floating-point type. If the value +is not a number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `float64` `number` + +#### Examples + +```ts +import { isFloat64, type MaybeFloat64 } from "jsr:@type/number/float64"; + +let x = 1.5 as MaybeFloat64, y = 0; + +if (isFloat64(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Float64`) +``` + +## `MaybeInt16` + +#### Signature + +```ts ignore +export type MaybeInt16 = Cast; +``` + +Casts a value into a partial signed 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int16` `number` + +#### Examples + +```ts +import { type Int16, isInt16, type MaybeInt16 } from "@nick/is/int16"; + +let value = 1 as Int16; + +const setValue = (newValue: MaybeInt16) => { + if (isInt16(newValue)) value = newValue; +}; + +setValue(0x7FFF); // <- No error! + +value = -32769; // Error: Type '-32769' is not assignable to type 'Int16'. +``` + +## `MaybeInt32` + +#### Signature + +```ts ignore +export type MaybeInt32 = Cast; +``` + +Casts a value into a partial signed 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int32` `number` + +#### Examples + +```ts +import { isInt32, type MaybeInt32 } from "jsr:@type/number/int32"; + +let value = 1 as MaybeInt32; + +const setValue = (newValue: MaybeInt32) => { + if (isInt32(newValue)) value = newValue; +}; + +setValue(0x7FFFFFFF); // <- No error! +value = -2147483649; // <- No error! (this is the main difference from `Int32`) +``` + +## `MaybeInt8` + +#### Signature + +```ts ignore +export type MaybeInt8 = Cast; +``` + +Casts a value into a partial signed 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `int8` `number` + +#### Examples + +```ts +import { isInt8, type MaybeInt8 } from "@nick/is/int8"; + +let i = 1 as MaybeInt8, y = 0; + +if (isInt8(i)) { + console.log(i); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Int8`) +``` + +## `MaybeInteger` + +#### Signature + +```ts ignore +export type MaybeInteger = N extends bigint + ? `${N}` extends `${infer I extends number}` ? N & MaybeInteger : never + : N extends number ? number extends N ? N & MAYBE_INTEGER + : `${N}` extends `${bigint}` ? N & MAYBE_INTEGER + : never + : never; +``` + +Casts a value into a partial integer type. If the value is not an number, or is +a non-integral number like 3.14, it will resolve to `never`. This type is nearly +identical to [Integer](#integer "Jump to symbol: 'Integer'"), except it allows +assignment of values that are not precisely compatible with the type, while +still providing an extra level of type safety over the base `number` type. + +Once a value is cast to a type of this constraint, TypeScript's compiler will +refuse any incompatible assignment to it. To demonstrate, consider this example: + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { + isInteger, + type MaybeFloat, + type MaybeInteger, +} from "jsr:@type/number"; + +function add(a: MaybeInteger, b: MaybeInteger) { + return (a + b) as MaybeInteger; +} + +let x = 1 as MaybeInteger, y = 2 as MaybeInteger, z = 3; +let xx = 1.1 as MaybeFloat, yy = 2.2 as MaybeFloat, zz = 3.3; + +if (isInteger(z)) { + console.log(add(add(x, y), z)); +} else { + console.log(add(x, y)); +} + +// These will raise TypeScript compiler errors: +add(x, yy); // <- TS2345 Type 'MaybeFloat' is not assignable to type 'MaybeInteger'. +y = yy; // <- TS2322 Type 'MaybeFloat' is not assignable to type 'MaybeInteger'. + +y = 2; // <- No error! (this is the main difference from `Integer`) +``` + +## `MaybeNaN` + +#### Signature + +```ts ignore +export type MaybeNaN = Cast; +``` + +Casts a value into a partial `NaN` type. This is a more forgiving form of the +[`NaN`](#nan "Jump to symbol: 'NaN'") type, which allows for the assignment of +other numeric values, but still retains the ability to distinguish itself from +generic numbers. This is often called a "Flavored" type, whereas the stricter +[`NaN`](#nan "Jump to symbol: 'NaN'") is known as a "Branded" type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNaN, type MaybeNaN } from "jsr:@type/number"; + +let x = NaN as MaybeNaN, y = 0; + +if (isNaN(x)) { + console.log(x); +} else { + console.log(y); +} + +y = NaN; // <- No error! (this is the main difference from `NaN`) +``` + +## `MaybeNegative` + +#### Signature + +```ts ignore +export type MaybeNegative = Cast; +``` + +Casts a value into a partial negative type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Types` `Numbers` + +###### Tags + +`maybe` `negative` `number` + +#### Examples + +```ts +import { isNegative, type MaybeNegative } from "jsr:@type/number"; + +let x = -1 as MaybeNegative, y = 0; + +if (isNegative(x)) { + console.log(x); +} else { + console.log(y); +} + +y = -1; // <- No error! (this is the main difference from `Negative`) +``` + +## `MaybeNegativeFinite` + +#### Signature + +```ts ignore +export type MaybeNegativeFinite = Cast; +``` + +Casts a value into a partial negative finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeNegativeNonZero` + +#### Signature + +```ts ignore +export type MaybeNegativeNonZero = Cast< + N, + MAYBE_NEGATIVE & MAYBE_NON_ZERO +>; +``` + +Casts a value into a partial negative nonzero type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeNegativeNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybeNegativeNonZeroFinite = Cast< + N, + MAYBE_NEGATIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a partial negative nonzero finite type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybeNegativeZero` + +#### Signature + +```ts ignore +export type MaybeNegativeZero = Cast; +``` + +Casts a value into a partial negative zero type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero, type MaybeNegativeZero } from "jsr:@type/number"; + +let x = -0 as MaybeNegativeZero, y = 0; + +if (isNegativeZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = -0; // <- No error! (this is the main difference from `NegativeZero`) +``` + +## `MaybeNonZero` + +#### Signature + +```ts ignore +export type MaybeNonZero = Cast; +``` + +Casts a value into a partial nonzero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero, type MaybeNonZero } from "jsr:@type/number"; + +let x = 1 as MaybeNonZero, y = 0; + +if (isNonZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `NonZero`) +``` + +## `MaybeNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybeNonZeroFinite = Cast; +``` + +Casts a value into a partial nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +## `MaybePositive` + +#### Signature + +```ts ignore +export type MaybePositive = Cast; +``` + +Casts a value into a partial positive type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `positive` `number` + +#### Examples + +```ts +import { isPositive, type MaybePositive } from "jsr:@type/number"; + +let x = 1 as MaybePositive, y = 0; + +if (isPositive(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Positive`) +``` + +## `MaybePositiveFinite` + +#### Signature + +```ts ignore +export type MaybePositiveFinite = Cast; +``` + +Casts a value into a partial positive finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybePositiveNonZero` + +#### Signature + +```ts ignore +export type MaybePositiveNonZero = Cast< + N, + MAYBE_POSITIVE & MAYBE_NON_ZERO +>; +``` + +Casts a value into a partial positive nonzero type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybePositiveNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybePositiveNonZeroFinite = Cast< + N, + MAYBE_POSITIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a partial positive nonzero finite type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `MaybePositiveZero` + +#### Signature + +```ts ignore +export type MaybePositiveZero = Cast; +``` + +Casts a value into a partial positive zero type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero, type MaybePositiveZero } from "jsr:@type/number"; + +let x = 0 as MaybePositiveZero, y = 1; + +if (isPositiveZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 0; // <- No error! (this is the main difference from `PositiveZero`) +``` + +## `MaybeUint16` + +#### Signature + +```ts ignore +export type MaybeUint16 = Cast; +``` + +Casts a value into a partial unsigned 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `MaybeUint32` + +#### Signature + +```ts ignore +export type MaybeUint32 = Cast; +``` + +Casts a value into a partial unsigned 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `MaybeUint8` + +#### Signature + +```ts ignore +export type MaybeUint8 = Cast; +``` + +Casts a value into a partial unsigned 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint8, type MaybeUint8 } from "@nick/is/uint8"; + +let i = 1 as MaybeUint8, y = 0; + +if (isUint8(i)) { + console.log(i); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Uint8`) +``` + +## `MaybeZero` + +#### Signature + +```ts ignore +export type MaybeZero = Cast; +``` + +Casts a value into a partial zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isZero, type MaybeZero } from "jsr:@type/number"; + +let x = 0 as MaybeZero, y = 1; + +if (isZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 0; // <- No error! (this is the main difference from `Zero`) +``` + +## `NaN` + +#### Signature + +```ts ignore +export type NaN = Cast; +``` + +Casts a value into a branded type that represents the special numeric value +`NaN` (not a number). This is a very strict type, and it prevents any other type +from being assigned unless they pass the +[`isNaN`](#isnan "Jump to symbol: 'isNaN'") type guard. If the value is not a +subtype of `number`, this will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNan, type NaN } from "jsr:@type/number"; + +let x = NaN as NaN, y = 0; + +if (isNan(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NaN'. +``` + +## `Negative` + +#### Signature + +```ts ignore +export type Negative = Cast; +``` + +Casts a value into a negative type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`negative` `number` + +#### Examples + +```ts +import { isNegative, type Negative } from "jsr:@type/number"; + +let x = -1 as Negative, y = 0; + +if (isNegative(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'Negative'. +``` + +## `NegativeBigInteger` + +#### Signature + +```ts ignore +export type NegativeBigInteger = CastInt; +``` + +Casts a value into a negative big integer type. If the value is not a bigint or +a string containing a valid integer, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `NegativeFinite` + +#### Signature + +```ts ignore +export type NegativeFinite = Cast; +``` + +Casts a value into a negative finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeFiniteInteger` + +#### Signature + +```ts ignore +export type NegativeFiniteInteger = Cast< + N, + NEGATIVE & FINITE & INTEGER +>; +``` + +Casts a value into a negative finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeInfinity` + +#### Signature + +```ts ignore +export type NegativeInfinity = -Infinity; +``` + +Special type representing negative infinity (`Number.NEGATIVE_INFINITY`). + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` `negative` + +## `NegativeInteger` + +#### Signature + +```ts ignore +export type NegativeInteger = Cast; +``` + +Casts a value into a negative integer type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZero` + +#### Signature + +```ts ignore +export type NegativeNonZero = Cast; +``` + +Casts a value into a negative nonzero type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZeroFinite` + +#### Signature + +```ts ignore +export type NegativeNonZeroFinite = Cast< + N, + NEGATIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a negative nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type NegativeNonZeroFiniteInteger = Cast< + N, + NEGATIVE & NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a negative nonzero finite integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZeroInteger` + +#### Signature + +```ts ignore +export type NegativeNonZeroInteger = Cast< + N, + NEGATIVE & NON_ZERO & INTEGER +>; +``` + +Casts a value into a negative nonzero integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeZero` + +#### Signature + +```ts ignore +export type NegativeZero = Cast; +``` + +Casts a value into a negative zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero, type NegativeZero } from "jsr:@type/number"; + +let x = -0 as NegativeZero, y = 0; + +if (isNegativeZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NegativeZero'. +``` + +## `NonZero` + +#### Signature + +```ts ignore +export type NonZero = Cast; +``` + +Casts a value into a nonzero type. If the value is not a number, it will resolve +to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero, type NonZero } from "jsr:@type/number"; + +let x = 1 as NonZero, y = 0; + +if (isNonZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NonZero'. +``` + +## `NonZeroFinite` + +#### Signature + +```ts ignore +export type NonZeroFinite = Cast; +``` + +Casts a value into a nonzero finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type NonZeroFiniteInteger = Cast< + N, + NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a nonzero finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NonZeroInteger` + +#### Signature + +```ts ignore +export type NonZeroInteger = Cast; +``` + +Casts a value into a nonzero integer type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `Numeric` + +#### Signature + +```ts ignore +export type Numeric = number | bigint | `${number | bigint}`; +``` + +## `Odd` + +#### Signature + +```ts ignore +export type Odd = Cast< + IsOdd, Extract, never>, + ODD +>; +``` + +Branded type representing an odd number. Used by overloads of the +[`isOdd`](#isodd "Jump to symbol: 'isOdd'") function to differentiate between +odd and even numbers. + +##### Type Parameters + +- **`T`** (default: `number`) + +--- + +###### Category + +`Numeric` + +## `Positive` + +#### Signature + +```ts ignore +export type Positive = Cast; +``` + +Casts a value into a positive type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive, type Positive } from "jsr:@type/number"; + +let x = 1 as Positive, y = 0; + +if (isPositive(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'Positive'. +``` + +## `PositiveBigInteger` + +#### Signature + +```ts ignore +export type PositiveBigInteger = CastInt; +``` + +Casts a value into a positive big integer type. If the value is not a bigint or +a string containing a valid integer, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `bigint`) + +--- + +###### Category + +`Numbers` + +## `PositiveFinite` + +#### Signature + +```ts ignore +export type PositiveFinite = Cast; +``` + +Casts a value into a positive finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveFiniteInteger` + +#### Signature + +```ts ignore +export type PositiveFiniteInteger = Cast< + N, + POSITIVE & FINITE & INTEGER +>; +``` + +Casts a value into a positive finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveInfinity` + +#### Signature + +```ts ignore +export type PositiveInfinity = Infinity; +``` + +Special type representing positive infinity (`Number.POSITIVE_INFINITY`). + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` `positive` + +## `PositiveInteger` + +#### Signature + +```ts ignore +export type PositiveInteger = Cast; +``` + +Casts a value into a positive finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZero` + +#### Signature + +```ts ignore +export type PositiveNonZero = Cast; +``` + +Casts a value into a positive nonzero type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZeroFinite` + +#### Signature + +```ts ignore +export type PositiveNonZeroFinite = Cast< + N, + POSITIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a positive nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type PositiveNonZeroFiniteInteger = Cast< + N, + POSITIVE & NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a positive nonzero finite integer type. If the value is not a +number, it will resolve to `never`.s + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZeroInteger` + +#### Signature + +```ts ignore +export type PositiveNonZeroInteger = Cast< + N, + POSITIVE & NON_ZERO & INTEGER +>; +``` + +Casts a value into a positive nonzero integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveZero` + +#### Signature + +```ts ignore +export type PositiveZero = Cast; +``` + +Casts a value into a positive zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero, type PositiveZero } from "jsr:@type/number"; + +let x = 0 as PositiveZero, y = 1; + +if (isPositiveZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'PositiveZero'. +``` + +## `Range` + +#### Signature + +```ts ignore +export type Range< + Min extends number = number, + Max extends number = number, + Tex extends Exclusivity = never, +> = [Tex] extends [never] ? + | RangeInclusiveMin + | RangeInclusive + | RangeInclusiveMax + | RangeExclusive + | RangeUnknown + : Either< + Extract, Required>>, + RangeUnknown + >; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `never`) + +--- + +## `RangeExclusive` + +#### Signature + +```ts ignore +export type RangeExclusive< + Min extends number = number, + Max extends number = number, +> = readonly [Min, Max, "()"] | readonly [Max, "()"]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `RangeInclusive` + +#### Signature + +```ts ignore +export type RangeInclusive< + Min extends number = number, + Max extends number = number, +> = readonly [Min, Max, "[]"] | readonly [Max, "[]"]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `RangeInclusiveMax` + +#### Signature + +```ts ignore +export type RangeInclusiveMax< + Min extends number = number, + Max extends number = number, +> = readonly [Min, Max, "(]"] | readonly [Max, "(]"]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `RangeInclusiveMin` + +#### Signature + +```ts ignore +export type RangeInclusiveMin< + Min extends number = number, + Max extends number = number, +> = readonly [Min, Max, "[)"] | readonly [Max, "[)"]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) + +--- + +## `RangeUnknown` + +#### Signature + +```ts ignore +export type RangeUnknown< + Min extends number = number, + Max extends number = number, + Tex extends Exclusivity = Exclusivity, +> = readonly [Min, Max, Tex] | readonly [Max, Tex]; +``` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `Exclusivity`) + +--- + +## `Uint16` + +#### Signature + +```ts ignore +export type Uint16 = Cast; +``` + +Casts a value into an unsigned 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `Uint32` + +#### Signature + +```ts ignore +export type Uint32 = Cast; +``` + +Casts a value into an unsigned 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `Uint8` + +#### Signature + +```ts ignore +export type Uint8 = Cast; +``` + +Casts a value into an unsigned 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint8, type Uint8 } from "@nick/is/uint8"; + +let i = 1 as Uint8, y = 0; + +if (isUint8(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint8'. +``` + +## `Unwrap` + +#### Signature + +```ts ignore +export type Unwrap = U extends Cast ? [N, T] : [U, never]; +``` + +Unwraps a type that has been cast with [Cast](#cast "Jump to symbol: 'Cast'") +into a tuple of the original value and the specific type it was cast to (or +"branded" with). If the given type was _not_ cast with +[Cast](#cast "Jump to symbol: 'Cast'"), it will resolve to a tuple containing +the original value and `never`, respectively. + +##### Type Parameters + +- **`U`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { Cast, Unwrap } from "jsr:@nick/is/number"; + +type Int_3 = Cast<3, INTEGER>; + +function unwrap(value: T): Unwrap[0] { + return value as Unwrap[0]; +} +``` + +## `Zero` + +#### Signature + +```ts ignore +export type Zero = Cast; +``` + +Casts a value into a zero type. If the value is not a number, it will resolve to +`never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isZero, type Zero } from "jsr:@type/number/zero"; + +let x = 0 as Zero, y = 1; + +if (isZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Zero'. +``` + +## `EVEN` + +### Properties + +#### IS_EVEN + +```ts +readonly IS_EVEN: true; +``` + +--- + +## `EVEN_INTEGER` + +## `FINITE` + +### Properties + +#### IS_INFINITE + +```ts +readonly IS_INFINITE: false; +``` + +#### IS_FINITE + +```ts +readonly IS_FINITE: true; +``` + +--- + +## `FLOAT` + +### Properties + +#### IS_FLOAT + +```ts +readonly IS_FLOAT: true; +``` + +--- + +## `FLOAT16` + +##### Extends `FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION: 0.5; +``` + +--- + +## `FLOAT32` + +##### Extends `FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION: 1; +``` + +--- + +## `FLOAT64` + +##### Extends `FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION: 2; +``` + +--- + +## `INFINITE` + +### Properties + +#### IS_FINITE + +```ts +readonly IS_FINITE: false; +``` + +#### IS_INFINITE + +```ts +readonly IS_INFINITE: true; +``` + +--- + +## `INT16` + +##### Extends `INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH: 16; +``` + +--- + +## `INT32` + +##### Extends `INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH: 32; +``` + +--- + +## `INT64` + +##### Extends `INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH: 64; +``` + +--- + +## `INT8` + +##### Extends `INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH: 8; +``` + +--- + +## `INTEGER` + +### Properties + +#### IS_INTEGER + +```ts +readonly IS_INTEGER: true; +``` + +--- + +## `IsInRange` + +##### Type Parameters + +- **`Min`** extends `number` (default: `number`) +- **`Max`** extends `number` (default: `number`) +- **`Tex`** extends `Exclusivity` (default: `Exclusivity`) + +--- + +### Properties + +#### RANGE + +```ts +readonly RANGE: readonly [Min,Max,Tex]; +``` + +--- + +## `MAYBE_EVEN` + +### Properties + +#### IS_EVEN + +```ts +readonly IS_EVEN?: true; +``` + +--- + +## `MAYBE_EVEN_INTEGER` + +## `MAYBE_FINITE` + +### Properties + +#### IS_INFINITE + +```ts +readonly IS_INFINITE?: false; +``` + +#### IS_FINITE + +```ts +readonly IS_FINITE?: true; +``` + +--- + +## `MAYBE_FLOAT` + +### Properties + +#### IS_FLOAT + +```ts +readonly IS_FLOAT?: true; +``` + +--- + +## `MAYBE_FLOAT16` + +##### Extends `MAYBE_FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION?: 0.5; +``` + +--- + +## `MAYBE_FLOAT32` + +##### Extends `MAYBE_FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION?: 1; +``` + +--- + +## `MAYBE_FLOAT64` + +##### Extends `MAYBE_FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION?: 2; +``` + +--- + +## `MAYBE_INFINITE` + +### Properties + +#### IS_FINITE + +```ts +readonly IS_FINITE?: false; +``` + +#### IS_INFINITE + +```ts +readonly IS_INFINITE?: true; +``` + +--- + +## `MAYBE_INT16` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH?: 16; +``` + +--- + +## `MAYBE_INT32` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH?: 32; +``` + +--- + +## `MAYBE_INT64` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH?: 64; +``` + +--- + +## `MAYBE_INT8` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH?: 8; +``` + +--- + +## `MAYBE_INTEGER` + +### Properties + +#### IS_INTEGER + +```ts +readonly IS_INTEGER?: true; +``` + +--- + +## `MAYBE_NAN` + +### Properties + +#### IS_NAN + +```ts +readonly IS_NAN?: true; +``` + +--- + +## `MAYBE_NEGATIVE` + +### Properties + +#### IS_POSITIVE + +```ts +readonly IS_POSITIVE?: false; +``` + +#### IS_NEGATIVE + +```ts +readonly IS_NEGATIVE?: true; +``` + +--- + +## `MAYBE_NEGATIVE_FINITE` + +## `MAYBE_NEGATIVE_INFINITY` + +## `MAYBE_NEGATIVE_INTEGER` + +## `MAYBE_NEGATIVE_NON_ZERO_FINITE` + +## `MAYBE_NEGATIVE_NON_ZERO_INTEGER` + +## `MAYBE_NEGATIVE_ZERO` + +## `MAYBE_NON_ZERO` + +### Properties + +#### IS_ZERO + +```ts +readonly IS_ZERO?: false; +``` + +#### IS_NON_ZERO + +```ts +readonly IS_NON_ZERO?: true; +``` + +--- + +## `MAYBE_NON_ZERO_FINITE` + +## `MAYBE_NON_ZERO_INTEGER` + +## `MAYBE_ODD` + +### Properties + +#### IS_ODD + +```ts +readonly IS_ODD?: true; +``` + +--- + +## `MAYBE_ODD_INTEGER` + +## `MAYBE_POSITIVE` + +### Properties + +#### IS_NEGATIVE + +```ts +readonly IS_NEGATIVE?: false; +``` + +#### IS_POSITIVE + +```ts +readonly IS_POSITIVE?: true; +``` + +--- + +## `MAYBE_POSITIVE_FINITE` + +## `MAYBE_POSITIVE_INFINITY` + +## `MAYBE_POSITIVE_INTEGER` + +## `MAYBE_POSITIVE_NON_ZERO_FINITE` + +## `MAYBE_POSITIVE_NON_ZERO_INTEGER` + +## `MAYBE_POSITIVE_ODD_INTEGER` + +## `MAYBE_POSITIVE_ZERO` + +## `MAYBE_UINT16` + +## `MAYBE_UINT32` + +## `MAYBE_UINT64` + +## `MAYBE_UINT8` + +## `MAYBE_UNSIGNED` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### IS_UNSIGNED + +```ts +readonly IS_UNSIGNED?: true; +``` + +--- + +## `MAYBE_ZERO` + +### Properties + +#### IS_NON_ZERO + +```ts +readonly IS_NON_ZERO?: false; +``` + +#### IS_ZERO + +```ts +readonly IS_ZERO?: true; +``` + +--- + +## `NAN` + +### Properties + +#### IS_NAN + +```ts +readonly IS_NAN: true; +``` + +--- + +## `NEGATIVE` + +### Properties + +#### IS_POSITIVE + +```ts +readonly IS_POSITIVE: false; +``` + +#### IS_NEGATIVE + +```ts +readonly IS_NEGATIVE: true; +``` + +--- + +## `NEGATIVE_FINITE` + +## `NEGATIVE_INFINITY` + +## `NEGATIVE_INTEGER` + +## `NEGATIVE_NON_ZERO_FINITE` + +## `NEGATIVE_NON_ZERO_INTEGER` + +## `NEGATIVE_ZERO` + +## `NON_ZERO` + +### Properties + +#### IS_ZERO + +```ts +readonly IS_ZERO: false; +``` + +#### IS_NON_ZERO + +```ts +readonly IS_NON_ZERO: true; +``` + +--- + +## `NON_ZERO_FINITE` + +## `NON_ZERO_INTEGER` + +## `ODD` + +### Properties + +#### IS_ODD + +```ts +readonly IS_ODD: true; +``` + +--- + +## `ODD_INTEGER` + +## `POSITIVE` + +### Properties + +#### IS_NEGATIVE + +```ts +readonly IS_NEGATIVE: false; +``` + +#### IS_POSITIVE + +```ts +readonly IS_POSITIVE: true; +``` + +--- + +## `POSITIVE_FINITE` + +## `POSITIVE_INFINITY` + +## `POSITIVE_INTEGER` + +## `POSITIVE_NON_ZERO_FINITE` + +## `POSITIVE_NON_ZERO_INTEGER` + +## `POSITIVE_ODD_INTEGER` + +## `POSITIVE_ZERO` + +## `UINT16` + +## `UINT32` + +## `UINT64` + +## `UINT8` + +## `UNSIGNED` + +##### Extends `INTEGER` + +### Properties + +#### IS_UNSIGNED + +```ts +readonly IS_UNSIGNED: true; +``` + +--- + +## `ZERO` + +### Properties + +#### IS_NON_ZERO + +```ts +readonly IS_NON_ZERO: false; +``` + +#### IS_ZERO + +```ts +readonly IS_ZERO: true; +``` + +--- diff --git a/docs/number/nan.md b/docs/number/nan.md new file mode 100644 index 0000000..d4f1967 --- /dev/null +++ b/docs/number/nan.md @@ -0,0 +1,172 @@ +# @nick/is/number/nan + +## `isNaN` + +#### Signature + +```ts ignore +function isNaN(it: N): it is NaN; +``` + +Checks if a given value is `NaN` (not a number). This is a type-safe alias of +the global `isNaN` function, + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `NaN`, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNaN } from "jsr:@type/number"; + +console.log(isNaN(0)); // false +console.log(isNaN(1)); // false +console.log(isNaN(1.5)); // false +console.log(isNaN(NaN)); // true +console.log(isNaN(Infinity)); // false +``` + +## `isNaN` + +#### Signature + +```ts ignore +function isNaN(it: unknown): it is NaN; +``` + +Checks if a given value is `NaN` (not a number). This is a type-safe alias of +the global `isNaN` function, + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is `NaN`, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNaN } from "jsr:@type/number"; + +console.log(isNaN(0)); // false +console.log(isNaN(1)); // false +console.log(isNaN(1.5)); // false +console.log(isNaN(NaN)); // true +console.log(isNaN(Infinity)); // false +``` + +## `MaybeNaN` + +#### Signature + +```ts ignore +export type MaybeNaN = Cast; +``` + +Casts a value into a partial `NaN` type. This is a more forgiving form of the +[`NaN`](#nan "Jump to symbol: 'NaN'") type, which allows for the assignment of +other numeric values, but still retains the ability to distinguish itself from +generic numbers. This is often called a "Flavored" type, whereas the stricter +[`NaN`](#nan "Jump to symbol: 'NaN'") is known as a "Branded" type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNaN, type MaybeNaN } from "jsr:@type/number"; + +let x = NaN as MaybeNaN, y = 0; + +if (isNaN(x)) { + console.log(x); +} else { + console.log(y); +} + +y = NaN; // <- No error! (this is the main difference from `NaN`) +``` + +## `NaN` + +#### Signature + +```ts ignore +export type NaN = Cast; +``` + +Casts a value into a branded type that represents the special numeric value +`NaN` (not a number). This is a very strict type, and it prevents any other type +from being assigned unless they pass the +[`isNaN`](#isnan "Jump to symbol: 'isNaN'") type guard. If the value is not a +subtype of `number`, this will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +###### Tags + +`number` `NaN` + +#### Examples + +```ts +import { isNan, type NaN } from "jsr:@type/number"; + +let x = NaN as NaN, y = 0; + +if (isNan(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NaN'. +``` diff --git a/docs/number/negative-finite-integer.md b/docs/number/negative-finite-integer.md new file mode 100644 index 0000000..f410b3d --- /dev/null +++ b/docs/number/negative-finite-integer.md @@ -0,0 +1,101 @@ +# @nick/is/number/negative-finite-integer + +## `isNegativeFiniteInteger` + +#### Signature + +```ts ignore +function isNegativeFiniteInteger( + it: N, +): it is NegativeFiniteInteger; +``` + +Checks if a given value is a negative finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteInteger(0)); // false +console.log(isNegativeFiniteInteger(1)); // false +console.log(isNegativeFiniteInteger(-1)); // true +console.log(isNegativeFiniteInteger(1.5)); // false +console.log(isNegativeFiniteInteger(NaN)); // false +console.log(isNegativeFiniteInteger(Infinity)); // false +``` + +## `isNegativeFiniteInteger` + +#### Signature + +```ts ignore +function isNegativeFiniteInteger(it: unknown): it is NegativeFiniteInteger; +``` + +Checks if a given value is a negative finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteInteger(0)); // false +console.log(isNegativeFiniteInteger(1)); // false +console.log(isNegativeFiniteInteger(-1)); // true +console.log(isNegativeFiniteInteger(1.5)); // false +console.log(isNegativeFiniteInteger(NaN)); // false +console.log(isNegativeFiniteInteger(Infinity)); // false +``` + +## `NegativeFiniteInteger` + +#### Signature + +```ts ignore +export type NegativeFiniteInteger = Cast< + N, + NEGATIVE & FINITE & INTEGER +>; +``` + +Casts a value into a negative finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/negative-finite.md b/docs/number/negative-finite.md new file mode 100644 index 0000000..35f78be --- /dev/null +++ b/docs/number/negative-finite.md @@ -0,0 +1,117 @@ +# @nick/is/number/negative-finite + +## `isNegativeFiniteNumber` + +#### Signature + +```ts ignore +function isNegativeFiniteNumber(it: N): it is NegativeFinite; +``` + +Checks if a given value is a negative finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteNumber(0)); // false +console.log(isNegativeFiniteNumber(1)); // false +console.log(isNegativeFiniteNumber(-1)); // true +console.log(isNegativeFiniteNumber(1.5)); // false +console.log(isNegativeFiniteNumber(NaN)); // false +console.log(isNegativeFiniteNumber(Infinity)); // false +``` + +## `isNegativeFiniteNumber` + +#### Signature + +```ts ignore +function isNegativeFiniteNumber(it: unknown): it is NegativeFinite; +``` + +Checks if a given value is a negative finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeFiniteNumber(0)); // false +console.log(isNegativeFiniteNumber(1)); // false +console.log(isNegativeFiniteNumber(-1)); // true +console.log(isNegativeFiniteNumber(1.5)); // false +console.log(isNegativeFiniteNumber(NaN)); // false +console.log(isNegativeFiniteNumber(Infinity)); // false +``` + +## `MaybeNegativeFinite` + +#### Signature + +```ts ignore +export type MaybeNegativeFinite = Cast; +``` + +Casts a value into a partial negative finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeFinite` + +#### Signature + +```ts ignore +export type NegativeFinite = Cast; +``` + +Casts a value into a negative finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/negative-infinity.md b/docs/number/negative-infinity.md new file mode 100644 index 0000000..0460d3a --- /dev/null +++ b/docs/number/negative-infinity.md @@ -0,0 +1,57 @@ +# @nick/is/number/negative-infinity + +## `isNegativeInfinity` + +#### Signature + +```ts ignore +function isNegativeInfinity(it: unknown): it is NegativeInfinity; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is negative infinity, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `negative` `infinity` + +#### Examples + +```ts +import { isNegativeInfinity } from "@nick/is/number/infinity"; + +console.log(isNegativeInfinity(Infinity)); // false +console.log(isNegativeInfinity(-Infinity)); // true +console.log(isNegativeInfinity(1)); // false +console.log(isNegativeInfinity(-1)); // false +console.log(isNegativeInfinity(NaN)); // false +``` + +## `NegativeInfinity` + +#### Signature + +```ts ignore +export type NegativeInfinity = -Infinity; +``` + +Special type representing negative infinity (`Number.NEGATIVE_INFINITY`). + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` `negative` diff --git a/docs/number/negative-integer.md b/docs/number/negative-integer.md new file mode 100644 index 0000000..b4036e6 --- /dev/null +++ b/docs/number/negative-integer.md @@ -0,0 +1,96 @@ +# @nick/is/number/negative-integer + +## `isNegativeInteger` + +#### Signature + +```ts ignore +function isNegativeInteger(it: N): it is NegativeInteger; +``` + +Checks if a given value is a negative integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeInteger(0)); // false +console.log(isNegativeInteger(1)); // false +console.log(isNegativeInteger(-1)); // true +console.log(isNegativeInteger(1.5)); // false +console.log(isNegativeInteger(NaN)); // false +console.log(isNegativeInteger(Infinity)); // false +``` + +## `isNegativeInteger` + +#### Signature + +```ts ignore +function isNegativeInteger(it: unknown): it is NegativeInteger; +``` + +Checks if a given value is a negative integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeInteger(0)); // false +console.log(isNegativeInteger(1)); // false +console.log(isNegativeInteger(-1)); // true +console.log(isNegativeInteger(1.5)); // false +console.log(isNegativeInteger(NaN)); // false +console.log(isNegativeInteger(Infinity)); // false +``` + +## `NegativeInteger` + +#### Signature + +```ts ignore +export type NegativeInteger = Cast; +``` + +Casts a value into a negative integer type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/negative-nonzero-finite-integer.md b/docs/number/negative-nonzero-finite-integer.md new file mode 100644 index 0000000..6da10e3 --- /dev/null +++ b/docs/number/negative-nonzero-finite-integer.md @@ -0,0 +1,103 @@ +# @nick/is/number/negative-nonzero-finite-integer + +## `isNegativeNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isNegativeNonZeroFiniteInteger( + it: N, +): it is NegativeNonZeroFiniteInteger; +``` + +Checks if a given value is a negative nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteInteger(0)); // false +console.log(isNegativeNonZeroFiniteInteger(1)); // false +console.log(isNegativeNonZeroFiniteInteger(-1)); // true +console.log(isNegativeNonZeroFiniteInteger(1.5)); // false +console.log(isNegativeNonZeroFiniteInteger(NaN)); // false +console.log(isNegativeNonZeroFiniteInteger(Infinity)); // false +``` + +## `isNegativeNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isNegativeNonZeroFiniteInteger( + it: unknown, +): it is NegativeNonZeroFiniteInteger; +``` + +Checks if a given value is a negative nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteInteger(0)); // false +console.log(isNegativeNonZeroFiniteInteger(1)); // false +console.log(isNegativeNonZeroFiniteInteger(-1)); // true +console.log(isNegativeNonZeroFiniteInteger(1.5)); // false +console.log(isNegativeNonZeroFiniteInteger(NaN)); // false +console.log(isNegativeNonZeroFiniteInteger(Infinity)); // false +``` + +## `NegativeNonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type NegativeNonZeroFiniteInteger = Cast< + N, + NEGATIVE & NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a negative nonzero finite integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/negative-nonzero-finite.md b/docs/number/negative-nonzero-finite.md new file mode 100644 index 0000000..a2fc636 --- /dev/null +++ b/docs/number/negative-nonzero-finite.md @@ -0,0 +1,127 @@ +# @nick/is/number/negative-nonzero-finite + +## `isNegativeNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isNegativeNonZeroFiniteNumber( + it: N, +): it is NegativeNonZeroFinite; +``` + +Checks if a given value is a negative nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteNumber(0)); // false +console.log(isNegativeNonZeroFiniteNumber(1)); // false +console.log(isNegativeNonZeroFiniteNumber(-1)); // true +console.log(isNegativeNonZeroFiniteNumber(1.5)); // false +console.log(isNegativeNonZeroFiniteNumber(NaN)); // false +console.log(isNegativeNonZeroFiniteNumber(Infinity)); // false +``` + +## `isNegativeNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isNegativeNonZeroFiniteNumber( + it: unknown, +): it is NegativeNonZeroFinite; +``` + +Checks if a given value is a negative nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroFiniteNumber(0)); // false +console.log(isNegativeNonZeroFiniteNumber(1)); // false +console.log(isNegativeNonZeroFiniteNumber(-1)); // true +console.log(isNegativeNonZeroFiniteNumber(1.5)); // false +console.log(isNegativeNonZeroFiniteNumber(NaN)); // false +console.log(isNegativeNonZeroFiniteNumber(Infinity)); // false +``` + +## `MaybeNegativeNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybeNegativeNonZeroFinite = Cast< + N, + MAYBE_NEGATIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a partial negative nonzero finite type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZeroFinite` + +#### Signature + +```ts ignore +export type NegativeNonZeroFinite = Cast< + N, + NEGATIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a negative nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/negative-nonzero-integer.md b/docs/number/negative-nonzero-integer.md new file mode 100644 index 0000000..9646f7f --- /dev/null +++ b/docs/number/negative-nonzero-integer.md @@ -0,0 +1,101 @@ +# @nick/is/number/negative-nonzero-integer + +## `isNegativeNonZeroInteger` + +#### Signature + +```ts ignore +function isNegativeNonZeroInteger( + it: N, +): it is NegativeNonZeroInteger; +``` + +Checks if a given value is a negative nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroInteger(0)); // false +console.log(isNegativeNonZeroInteger(1)); // false +console.log(isNegativeNonZeroInteger(-1)); // true +console.log(isNegativeNonZeroInteger(1.5)); // false +console.log(isNegativeNonZeroInteger(NaN)); // false +console.log(isNegativeNonZeroInteger(Infinity)); // true +``` + +## `isNegativeNonZeroInteger` + +#### Signature + +```ts ignore +function isNegativeNonZeroInteger(it: unknown): it is NegativeNonZeroInteger; +``` + +Checks if a given value is a negative nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroInteger(0)); // false +console.log(isNegativeNonZeroInteger(1)); // false +console.log(isNegativeNonZeroInteger(-1)); // true +console.log(isNegativeNonZeroInteger(1.5)); // false +console.log(isNegativeNonZeroInteger(NaN)); // false +console.log(isNegativeNonZeroInteger(Infinity)); // true +``` + +## `NegativeNonZeroInteger` + +#### Signature + +```ts ignore +export type NegativeNonZeroInteger = Cast< + N, + NEGATIVE & NON_ZERO & INTEGER +>; +``` + +Casts a value into a negative nonzero integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/negative-nonzero.md b/docs/number/negative-nonzero.md new file mode 100644 index 0000000..11c058a --- /dev/null +++ b/docs/number/negative-nonzero.md @@ -0,0 +1,112 @@ +# @nick/is/number/negative-nonzero + +## `isNegativeNonZeroNumber` + +#### Signature + +```ts ignore +function isNegativeNonZeroNumber(it: N): it is NegativeNonZero; +``` + +Checks if a given value is a negative nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero number, `false` otherwise. + +#### Examples + +```ts +import { isNegativeNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroNumber(0)); // false +console.log(isNegativeNonZeroNumber(1)); // false +console.log(isNegativeNonZeroNumber(-1)); // true +console.log(isNegativeNonZeroNumber(1.5)); // false +console.log(isNegativeNonZeroNumber(NaN)); // false +console.log(isNegativeNonZeroNumber(Infinity)); // false +``` + +## `isNegativeNonZeroNumber` + +#### Signature + +```ts ignore +function isNegativeNonZeroNumber(it: unknown): it is NegativeNonZero; +``` + +Checks if a given value is a negative nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative nonzero number, `false` otherwise. + +#### Examples + +```ts +import { isNegativeNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isNegativeNonZeroNumber(0)); // false +console.log(isNegativeNonZeroNumber(1)); // false +console.log(isNegativeNonZeroNumber(-1)); // true +console.log(isNegativeNonZeroNumber(1.5)); // false +console.log(isNegativeNonZeroNumber(NaN)); // false +console.log(isNegativeNonZeroNumber(Infinity)); // false +``` + +## `MaybeNegativeNonZero` + +#### Signature + +```ts ignore +export type MaybeNegativeNonZero = Cast< + N, + MAYBE_NEGATIVE & MAYBE_NON_ZERO +>; +``` + +Casts a value into a partial negative nonzero type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `NegativeNonZero` + +#### Signature + +```ts ignore +export type NegativeNonZero = Cast; +``` + +Casts a value into a negative nonzero type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/negative-zero.md b/docs/number/negative-zero.md new file mode 100644 index 0000000..cdbe80d --- /dev/null +++ b/docs/number/negative-zero.md @@ -0,0 +1,164 @@ +# @nick/is/number/negative-zero + +## `isNegativeZero` + +#### Signature + +```ts ignore +function isNegativeZero(it: N): it is NegativeZero; +``` + +Checks if a given value is negative zero, which is a special numeric value in +JavaScript, distinctly different from it's positive counterpart. Checking for +negative zero involves more than simply `x === -0`, as `-0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `-0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is negative zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero } from "jsr:@nick/is/number"; + +console.log(isNegativeZero(-0)); // true +console.log(isNegativeZero(0)); // false +console.log(isNegativeZero(-1)); // false +console.log(isNegativeZero(1)); // false +``` + +## `isNegativeZero` + +#### Signature + +```ts ignore +function isNegativeZero(it: unknown): it is NegativeZero; +``` + +Checks if a given value is negative zero, which is a special numeric value in +JavaScript, distinctly different from it's positive counterpart. Checking for +negative zero involves more than simply `x === -0`, as `-0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `-0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is negative zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero } from "jsr:@nick/is/number"; + +console.log(isNegativeZero(-0)); // true +console.log(isNegativeZero(0)); // false +console.log(isNegativeZero(-1)); // false +console.log(isNegativeZero(1)); // false +``` + +## `MaybeNegativeZero` + +#### Signature + +```ts ignore +export type MaybeNegativeZero = Cast; +``` + +Casts a value into a partial negative zero type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero, type MaybeNegativeZero } from "jsr:@type/number"; + +let x = -0 as MaybeNegativeZero, y = 0; + +if (isNegativeZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = -0; // <- No error! (this is the main difference from `NegativeZero`) +``` + +## `NegativeZero` + +#### Signature + +```ts ignore +export type NegativeZero = Cast; +``` + +Casts a value into a negative zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNegativeZero, type NegativeZero } from "jsr:@type/number"; + +let x = -0 as NegativeZero, y = 0; + +if (isNegativeZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NegativeZero'. +``` diff --git a/docs/number/negative.md b/docs/number/negative.md new file mode 100644 index 0000000..56d9d5a --- /dev/null +++ b/docs/number/negative.md @@ -0,0 +1,172 @@ +# @nick/is/number/negative + +## `isNegative` + +#### Signature + +```ts ignore +function isNegative(it: N): it is Negative; +``` + +Checks if a given value is a negative number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`negative` + +#### Examples + +```ts +import { isNegative } from "jsr:@nick/is/integer"; + +console.log(isNegative(0)); // false +console.log(isNegative(1)); // false +console.log(isNegative(1.5)); // false +console.log(isNegative(NaN)); // false +console.log(isNegative(Infinity)); // false + +console.log(isNegative(-0)); // true +console.log(isNegative(-1)); // true +console.log(isNegative(-Infinity)); // true +``` + +## `isNegative` + +#### Signature + +```ts ignore +function isNegative(it: unknown): it is Negative; +``` + +Checks if a given value is a negative number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a negative number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`negative` + +#### Examples + +```ts +import { isNegative } from "jsr:@nick/is/integer"; + +console.log(isNegative(0)); // false +console.log(isNegative(1)); // false +console.log(isNegative(1.5)); // false +console.log(isNegative(NaN)); // false +console.log(isNegative(Infinity)); // false + +console.log(isNegative(-0)); // true +console.log(isNegative(-1)); // true +console.log(isNegative(-Infinity)); // true +``` + +## `MaybeNegative` + +#### Signature + +```ts ignore +export type MaybeNegative = Cast; +``` + +Casts a value into a partial negative type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Types` `Numbers` + +###### Tags + +`maybe` `negative` `number` + +#### Examples + +```ts +import { isNegative, type MaybeNegative } from "jsr:@type/number"; + +let x = -1 as MaybeNegative, y = 0; + +if (isNegative(x)) { + console.log(x); +} else { + console.log(y); +} + +y = -1; // <- No error! (this is the main difference from `Negative`) +``` + +## `Negative` + +#### Signature + +```ts ignore +export type Negative = Cast; +``` + +Casts a value into a negative type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`negative` `number` + +#### Examples + +```ts +import { isNegative, type Negative } from "jsr:@type/number"; + +let x = -1 as Negative, y = 0; + +if (isNegative(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'Negative'. +``` diff --git a/docs/number/nonzero-finite-integer.md b/docs/number/nonzero-finite-integer.md new file mode 100644 index 0000000..4393d59 --- /dev/null +++ b/docs/number/nonzero-finite-integer.md @@ -0,0 +1,101 @@ +# @nick/is/number/nonzero-finite-integer + +## `isNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isNonZeroFiniteInteger( + it: N, +): it is NonZeroFiniteInteger; +``` + +Checks if a given value is a nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteInteger(0)); // false +console.log(isNonZeroFiniteInteger(1)); // true +console.log(isNonZeroFiniteInteger(-1)); // true +console.log(isNonZeroFiniteInteger(1.5)); // false +console.log(isNonZeroFiniteInteger(NaN)); // false +console.log(isNonZeroFiniteInteger(Infinity)); // true +``` + +## `isNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isNonZeroFiniteInteger(it: unknown): it is NonZeroFiniteInteger; +``` + +Checks if a given value is a nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteInteger(0)); // false +console.log(isNonZeroFiniteInteger(1)); // true +console.log(isNonZeroFiniteInteger(-1)); // true +console.log(isNonZeroFiniteInteger(1.5)); // false +console.log(isNonZeroFiniteInteger(NaN)); // false +console.log(isNonZeroFiniteInteger(Infinity)); // true +``` + +## `NonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type NonZeroFiniteInteger = Cast< + N, + NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a nonzero finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/nonzero-finite.md b/docs/number/nonzero-finite.md new file mode 100644 index 0000000..0b4ee62 --- /dev/null +++ b/docs/number/nonzero-finite.md @@ -0,0 +1,113 @@ +# @nick/is/number/nonzero-finite + +## `isNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isNonZeroFiniteNumber(it: N): it is NonZeroFinite; +``` + +Checks if a given value is a nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteNumber(0)); // false +console.log(isNonZeroFiniteNumber(1)); // true +console.log(isNonZeroFiniteNumber(-1)); // true +console.log(isNonZeroFiniteNumber(1.5)); // true +console.log(isNonZeroFiniteNumber(NaN)); // false +console.log(isNonZeroFiniteNumber(Infinity)); // true +``` + +## `isNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isNonZeroFiniteNumber(it: unknown): it is NonZeroFinite; +``` + +Checks if a given value is a nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isNonZeroFiniteNumber(0)); // false +console.log(isNonZeroFiniteNumber(1)); // true +console.log(isNonZeroFiniteNumber(-1)); // true +console.log(isNonZeroFiniteNumber(1.5)); // true +console.log(isNonZeroFiniteNumber(NaN)); // false +console.log(isNonZeroFiniteNumber(Infinity)); // true +``` + +## `MaybeNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybeNonZeroFinite = Cast; +``` + +Casts a value into a partial nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +## `NonZeroFinite` + +#### Signature + +```ts ignore +export type NonZeroFinite = Cast; +``` + +Casts a value into a nonzero finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/nonzero-integer.md b/docs/number/nonzero-integer.md new file mode 100644 index 0000000..ce01f09 --- /dev/null +++ b/docs/number/nonzero-integer.md @@ -0,0 +1,96 @@ +# @nick/is/number/nonzero-integer + +## `isNonZeroInteger` + +#### Signature + +```ts ignore +function isNonZeroInteger(it: N): it is NonZeroInteger; +``` + +Checks if a given value is a nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroInteger(0)); // false +console.log(isNonZeroInteger(1)); // true +console.log(isNonZeroInteger(-1)); // true +console.log(isNonZeroInteger(1.5)); // false +console.log(isNonZeroInteger(NaN)); // false +console.log(isNonZeroInteger(Infinity)); // true +``` + +## `isNonZeroInteger` + +#### Signature + +```ts ignore +function isNonZeroInteger(it: unknown): it is NonZeroInteger; +``` + +Checks if a given value is a nonzero integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isNonZeroInteger(0)); // false +console.log(isNonZeroInteger(1)); // true +console.log(isNonZeroInteger(-1)); // true +console.log(isNonZeroInteger(1.5)); // false +console.log(isNonZeroInteger(NaN)); // false +console.log(isNonZeroInteger(Infinity)); // true +``` + +## `NonZeroInteger` + +#### Signature + +```ts ignore +export type NonZeroInteger = Cast; +``` + +Casts a value into a nonzero integer type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/nonzero.md b/docs/number/nonzero.md new file mode 100644 index 0000000..850361b --- /dev/null +++ b/docs/number/nonzero.md @@ -0,0 +1,154 @@ +# @nick/is/number/nonzero + +## `isNonZero` + +#### Signature + +```ts ignore +function isNonZero(it: N): it is NonZero; +``` + +Checks if a given value is a nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero } from "jsr:@nick/is/number/nonzero"; + +console.log(isNonZero(1)); // true +console.log(isNonZero(-1)); // true +console.log(isNonZero(1.5)); // true + +console.log(isNonZero(0)); // false +console.log(isNonZero(-0)); // false +console.log(isNonZero(NaN)); // false +console.log(isNonZero(Infinity)); // true +``` + +## `isNonZero` + +#### Signature + +```ts ignore +function isNonZero(it: unknown): it is NonZero; +``` + +Checks if a given value is a nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero } from "jsr:@nick/is/number/nonzero"; + +console.log(isNonZero(1)); // true +console.log(isNonZero(-1)); // true +console.log(isNonZero(1.5)); // true + +console.log(isNonZero(0)); // false +console.log(isNonZero(-0)); // false +console.log(isNonZero(NaN)); // false +console.log(isNonZero(Infinity)); // true +``` + +## `MaybeNonZero` + +#### Signature + +```ts ignore +export type MaybeNonZero = Cast; +``` + +Casts a value into a partial nonzero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero, type MaybeNonZero } from "jsr:@type/number"; + +let x = 1 as MaybeNonZero, y = 0; + +if (isNonZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `NonZero`) +``` + +## `NonZero` + +#### Signature + +```ts ignore +export type NonZero = Cast; +``` + +Casts a value into a nonzero type. If the value is not a number, it will resolve +to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isNonZero, type NonZero } from "jsr:@type/number"; + +let x = 1 as NonZero, y = 0; + +if (isNonZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'NonZero'. +``` diff --git a/docs/number/number.md b/docs/number/number.md new file mode 100644 index 0000000..d5b14a4 --- /dev/null +++ b/docs/number/number.md @@ -0,0 +1,45 @@ +# @nick/is/number/number + +## `isNumber` + +#### Signature + +```ts ignore +function isNumber(it: unknown): it is number; +``` + +Checks if the given value is a number. This includes all numbers, without +distinguishing between `NaN`, `Infinity`, and other special values. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a number, `false` otherwise. + +###### Category + +`Primitives` + +#### Examples + +```ts +import { isNumber } from "jsr:@nick/is/number"; + +isNumber("123"); // false +isNumber(123); // true +``` + +```ts +import { isNumber } from "jsr:@nick/is/number"; + +const x: unknown = 123; +if (isNumber(x)) { + console.log(x + 1); + // ^? const x: number +} +``` diff --git a/docs/number/odd.md b/docs/number/odd.md new file mode 100644 index 0000000..cb26787 --- /dev/null +++ b/docs/number/odd.md @@ -0,0 +1,203 @@ +# @nick/is/number/odd + +## `isOdd` + +#### Signature + +```ts ignore +function isOdd(it: T): it is Odd; +``` + +Checks if a given number / bigint is odd. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :----------------------------------------------------------------- | +| **`it`** | The number or bigint to check, either literal or in string format. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOdd` + +#### Signature + +```ts ignore +function isOdd(it: number | `${number}`): it is Odd; +``` + +Checks if a given number / numeric string is odd. Returns `true` if the value is +not divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------- | +| **`it`** | The number or numeric string to check. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOdd` + +#### Signature + +```ts ignore +function isOdd(it: bigint | `${bigint}`): it is Odd; +``` + +Checks if a given bigint or bigint string is an odd number. Returns `true` if +the value is not divisible by `2`, and `false` otherwise. This usually +corresponds to integers that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------------------------ | +| **`it`** | The bigint or bigint string to check. | + +##### Returns + +`true` if the value is odd, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `isOdd` + +#### Signature + +```ts ignore +function isOdd(it: unknown): it is Odd; +``` + +Checks if a given number / bigint is odd. Returns `true` if the value is not +divisible by `2`, and `false` otherwise. This usually corresponds to numbers +that end in `1`, `3`, `5`, `7`, or `9`. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is an odd finite integer, `false` otherwise. + +###### Category + +`Numeric` + +#### Examples + +```ts +import { isOdd } from "@nick/is/odd"; + +isOdd(1); // true +isOdd(2); // false +isOdd(3n); // true +isOdd(4n); // false +``` + +## `IsOdd` + +#### Signature + +```ts ignore +export type IsOdd = + `${number}` extends `${T}` ? True + : `${bigint}` extends `${T}` ? True + : `${T}` extends `${infer _}${1 | 3 | 5 | 7 | 9}` ? True + : False; +``` + +Type-level equivalent of [`isOdd`](#isodd "Jump to symbol: 'isOdd'"), which +checks if a given numeric type (number or bigint) ends in an odd number. Returns +[True](#true "Jump to symbol: 'True'") if so, and +[False](#false "Jump to symbol: 'False'") otherwise. + +##### Type Parameters + +- **`T`** extends `Numeric` +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Numeric` + +## `Odd` + +#### Signature + +```ts ignore +export type Odd = Cast< + IsOdd, Extract, never>, + ODD +>; +``` + +Branded type representing an odd number. Used by overloads of the +[`isOdd`](#isodd "Jump to symbol: 'isOdd'") function to differentiate between +odd and even numbers. + +##### Type Parameters + +- **`T`** (default: `number`) + +--- + +###### Category + +`Numeric` diff --git a/docs/number/positive-finite-integer.md b/docs/number/positive-finite-integer.md new file mode 100644 index 0000000..79ae3bd --- /dev/null +++ b/docs/number/positive-finite-integer.md @@ -0,0 +1,101 @@ +# @nick/is/number/positive-finite-integer + +## `isPositiveFiniteInteger` + +#### Signature + +```ts ignore +function isPositiveFiniteInteger( + it: N, +): it is PositiveFiniteInteger; +``` + +Checks if a given value is a positive finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteInteger(0)); // false +console.log(isPositiveFiniteInteger(1)); // true +console.log(isPositiveFiniteInteger(-1)); // false +console.log(isPositiveFiniteInteger(1.5)); // false +console.log(isPositiveFiniteInteger(NaN)); // false +console.log(isPositiveFiniteInteger(Infinity)); // false +``` + +## `isPositiveFiniteInteger` + +#### Signature + +```ts ignore +function isPositiveFiniteInteger(it: unknown): it is PositiveFiniteInteger; +``` + +Checks if a given value is a positive finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteInteger(0)); // false +console.log(isPositiveFiniteInteger(1)); // true +console.log(isPositiveFiniteInteger(-1)); // false +console.log(isPositiveFiniteInteger(1.5)); // false +console.log(isPositiveFiniteInteger(NaN)); // false +console.log(isPositiveFiniteInteger(Infinity)); // false +``` + +## `PositiveFiniteInteger` + +#### Signature + +```ts ignore +export type PositiveFiniteInteger = Cast< + N, + POSITIVE & FINITE & INTEGER +>; +``` + +Casts a value into a positive finite integer type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/positive-finite.md b/docs/number/positive-finite.md new file mode 100644 index 0000000..7a6134a --- /dev/null +++ b/docs/number/positive-finite.md @@ -0,0 +1,117 @@ +# @nick/is/number/positive-finite + +## `isPositiveFiniteNumber` + +#### Signature + +```ts ignore +function isPositiveFiniteNumber(it: N): it is PositiveFinite; +``` + +Checks if a given value is a positive finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteNumber(0)); // false +console.log(isPositiveFiniteNumber(1)); // true +console.log(isPositiveFiniteNumber(-1)); // false +console.log(isPositiveFiniteNumber(1.5)); // true +console.log(isPositiveFiniteNumber(NaN)); // false +console.log(isPositiveFiniteNumber(Infinity)); // false +``` + +## `isPositiveFiniteNumber` + +#### Signature + +```ts ignore +function isPositiveFiniteNumber(it: unknown): it is PositiveFinite; +``` + +Checks if a given value is a positive finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveFiniteNumber(0)); // false +console.log(isPositiveFiniteNumber(1)); // true +console.log(isPositiveFiniteNumber(-1)); // false +console.log(isPositiveFiniteNumber(1.5)); // true +console.log(isPositiveFiniteNumber(NaN)); // false +console.log(isPositiveFiniteNumber(Infinity)); // false +``` + +## `MaybePositiveFinite` + +#### Signature + +```ts ignore +export type MaybePositiveFinite = Cast; +``` + +Casts a value into a partial positive finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveFinite` + +#### Signature + +```ts ignore +export type PositiveFinite = Cast; +``` + +Casts a value into a positive finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/positive-infinity.md b/docs/number/positive-infinity.md new file mode 100644 index 0000000..f095e0e --- /dev/null +++ b/docs/number/positive-infinity.md @@ -0,0 +1,57 @@ +# @nick/is/number/positive-infinity + +## `isPositiveInfinity` + +#### Signature + +```ts ignore +function isPositiveInfinity(it: unknown): it is PositiveInfinity; +``` + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is positive infinity, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `positive` `infinity` + +#### Examples + +```ts +import { isPositiveInfinity } from "@nick/is/number/infinity"; + +console.log(isPositiveInfinity(Infinity)); // false +console.log(isPositiveInfinity(-Infinity)); // true +console.log(isPositiveInfinity(1)); // false +console.log(isPositiveInfinity(-1)); // false +console.log(isPositiveInfinity(NaN)); // false +``` + +## `PositiveInfinity` + +#### Signature + +```ts ignore +export type PositiveInfinity = Infinity; +``` + +Special type representing positive infinity (`Number.POSITIVE_INFINITY`). + +###### Category + +`Numbers` + +###### Tags + +`types` `number` `infinity` `positive` diff --git a/docs/number/positive-integer.md b/docs/number/positive-integer.md new file mode 100644 index 0000000..49ab3fe --- /dev/null +++ b/docs/number/positive-integer.md @@ -0,0 +1,96 @@ +# @nick/is/number/positive-integer + +## `isPositiveInteger` + +#### Signature + +```ts ignore +function isPositiveInteger(it: N): it is PositiveInteger; +``` + +Checks if a given value is a positive integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveInteger(0)); // true +console.log(isPositiveInteger(1)); // true +console.log(isPositiveInteger(-1)); // false +console.log(isPositiveInteger(1.5)); // false +console.log(isPositiveInteger(NaN)); // false +console.log(isPositiveInteger(Infinity)); // false +``` + +## `isPositiveInteger` + +#### Signature + +```ts ignore +function isPositiveInteger(it: unknown): it is PositiveInteger; +``` + +Checks if a given value is a positive integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveInteger(0)); // true +console.log(isPositiveInteger(1)); // true +console.log(isPositiveInteger(-1)); // false +console.log(isPositiveInteger(1.5)); // false +console.log(isPositiveInteger(NaN)); // false +console.log(isPositiveInteger(Infinity)); // false +``` + +## `PositiveInteger` + +#### Signature + +```ts ignore +export type PositiveInteger = Cast; +``` + +Casts a value into a positive finite type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/positive-nonzero-finite-integer.md b/docs/number/positive-nonzero-finite-integer.md new file mode 100644 index 0000000..a5844c0 --- /dev/null +++ b/docs/number/positive-nonzero-finite-integer.md @@ -0,0 +1,103 @@ +# @nick/is/number/positive-nonzero-finite-integer + +## `isPositiveNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isPositiveNonZeroFiniteInteger( + it: N, +): it is PositiveNonZeroFiniteInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteInteger(0)); // false +console.log(isPositiveNonZeroFiniteInteger(1)); // true +console.log(isPositiveNonZeroFiniteInteger(-1)); // false +console.log(isPositiveNonZeroFiniteInteger(1.5)); // false +console.log(isPositiveNonZeroFiniteInteger(NaN)); // false +console.log(isPositiveNonZeroFiniteInteger(Infinity)); // true +``` + +## `isPositiveNonZeroFiniteInteger` + +#### Signature + +```ts ignore +function isPositiveNonZeroFiniteInteger( + it: unknown, +): it is PositiveNonZeroFiniteInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteInteger(0)); // false +console.log(isPositiveNonZeroFiniteInteger(1)); // true +console.log(isPositiveNonZeroFiniteInteger(-1)); // false +console.log(isPositiveNonZeroFiniteInteger(1.5)); // false +console.log(isPositiveNonZeroFiniteInteger(NaN)); // false +console.log(isPositiveNonZeroFiniteInteger(Infinity)); // true +``` + +## `PositiveNonZeroFiniteInteger` + +#### Signature + +```ts ignore +export type PositiveNonZeroFiniteInteger = Cast< + N, + POSITIVE & NON_ZERO & FINITE & INTEGER +>; +``` + +Casts a value into a positive nonzero finite integer type. If the value is not a +number, it will resolve to `never`.s + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/positive-nonzero-finite.md b/docs/number/positive-nonzero-finite.md new file mode 100644 index 0000000..426d925 --- /dev/null +++ b/docs/number/positive-nonzero-finite.md @@ -0,0 +1,127 @@ +# @nick/is/number/positive-nonzero-finite + +## `isPositiveNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroFiniteNumber( + it: N, +): it is PositiveNonZeroFinite; +``` + +Checks if a given value is a positive nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteNumber(0)); // false +console.log(isPositiveNonZeroFiniteNumber(1)); // true +console.log(isPositiveNonZeroFiniteNumber(-1)); // false +console.log(isPositiveNonZeroFiniteNumber(1.5)); // true +console.log(isPositiveNonZeroFiniteNumber(NaN)); // false +console.log(isPositiveNonZeroFiniteNumber(Infinity)); // true +``` + +## `isPositiveNonZeroFiniteNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroFiniteNumber( + it: unknown, +): it is PositiveNonZeroFinite; +``` + +Checks if a given value is a positive nonzero finite number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroFiniteNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroFiniteNumber(0)); // false +console.log(isPositiveNonZeroFiniteNumber(1)); // true +console.log(isPositiveNonZeroFiniteNumber(-1)); // false +console.log(isPositiveNonZeroFiniteNumber(1.5)); // true +console.log(isPositiveNonZeroFiniteNumber(NaN)); // false +console.log(isPositiveNonZeroFiniteNumber(Infinity)); // true +``` + +## `MaybePositiveNonZeroFinite` + +#### Signature + +```ts ignore +export type MaybePositiveNonZeroFinite = Cast< + N, + MAYBE_POSITIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a partial positive nonzero finite type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZeroFinite` + +#### Signature + +```ts ignore +export type PositiveNonZeroFinite = Cast< + N, + POSITIVE_NON_ZERO_FINITE +>; +``` + +Casts a value into a positive nonzero finite type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/positive-nonzero-integer.md b/docs/number/positive-nonzero-integer.md new file mode 100644 index 0000000..d18332a --- /dev/null +++ b/docs/number/positive-nonzero-integer.md @@ -0,0 +1,101 @@ +# @nick/is/number/positive-nonzero-integer + +## `isPositiveNonZeroInteger` + +#### Signature + +```ts ignore +function isPositiveNonZeroInteger( + it: N, +): it is PositiveNonZeroInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroInteger(0)); // false +console.log(isPositiveNonZeroInteger(1)); // true +console.log(isPositiveNonZeroInteger(-1)); // false +console.log(isPositiveNonZeroInteger(1.5)); // false +console.log(isPositiveNonZeroInteger(NaN)); // false +console.log(isPositiveNonZeroInteger(Infinity)); // true +``` + +## `isPositiveNonZeroInteger` + +#### Signature + +```ts ignore +function isPositiveNonZeroInteger(it: unknown): it is PositiveNonZeroInteger; +``` + +Checks if a given value is a positive nonzero finite integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero finite integer, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroInteger } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroInteger(0)); // false +console.log(isPositiveNonZeroInteger(1)); // true +console.log(isPositiveNonZeroInteger(-1)); // false +console.log(isPositiveNonZeroInteger(1.5)); // false +console.log(isPositiveNonZeroInteger(NaN)); // false +console.log(isPositiveNonZeroInteger(Infinity)); // true +``` + +## `PositiveNonZeroInteger` + +#### Signature + +```ts ignore +export type PositiveNonZeroInteger = Cast< + N, + POSITIVE & NON_ZERO & INTEGER +>; +``` + +Casts a value into a positive nonzero integer type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/positive-nonzero.md b/docs/number/positive-nonzero.md new file mode 100644 index 0000000..04ece2b --- /dev/null +++ b/docs/number/positive-nonzero.md @@ -0,0 +1,128 @@ +# @nick/is/number/positive-nonzero + +## `isPositiveNonZeroNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroNumber(it: N): it is PositiveNonZero; +``` + +Checks if a given value is a positive nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroNumber(0)); // false +console.log(isPositiveNonZeroNumber(1)); // true +console.log(isPositiveNonZeroNumber(-1)); // false +console.log(isPositiveNonZeroNumber(1.5)); // true +console.log(isPositiveNonZeroNumber(NaN)); // false +console.log(isPositiveNonZeroNumber(Infinity)); // true +``` + +## `isPositiveNonZeroNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroNumber(it: unknown): it is PositiveNonZero; +``` + +Checks if a given value is a positive nonzero number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive nonzero number, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveNonZeroNumber } from "jsr:@nick/is/integer"; + +console.log(isPositiveNonZeroNumber(0)); // false +console.log(isPositiveNonZeroNumber(1)); // true +console.log(isPositiveNonZeroNumber(-1)); // false +console.log(isPositiveNonZeroNumber(1.5)); // true +console.log(isPositiveNonZeroNumber(NaN)); // false +console.log(isPositiveNonZeroNumber(Infinity)); // true +``` + +## `isPositiveNonZeroNumber` + +#### Signature + +```ts ignore +function isPositiveNonZeroNumber(it: unknown): it is PositiveNonZero; +``` + +## `MaybePositiveNonZero` + +#### Signature + +```ts ignore +export type MaybePositiveNonZero = Cast< + N, + MAYBE_POSITIVE & MAYBE_NON_ZERO +>; +``` + +Casts a value into a partial positive nonzero type. If the value is not a +number, it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +## `PositiveNonZero` + +#### Signature + +```ts ignore +export type PositiveNonZero = Cast; +``` + +Casts a value into a positive nonzero type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` diff --git a/docs/number/positive-zero.md b/docs/number/positive-zero.md new file mode 100644 index 0000000..3393ea7 --- /dev/null +++ b/docs/number/positive-zero.md @@ -0,0 +1,164 @@ +# @nick/is/number/positive-zero + +## `isPositiveZero` + +#### Signature + +```ts ignore +function isPositiveZero(it: N): it is PositiveZero; +``` + +Checks if a given value is positive zero, which is a special numeric value in +JavaScript, distinctly different from it's negative counterpart. Checking for +positive zero involves more than simply `x === +0`, as `+0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `+0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is positive zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero } from "jsr:@nick/is/number"; + +console.log(isPositiveZero(-0)); // false +console.log(isPositiveZero(0)); // true +console.log(isPositiveZero(-1)); // false +console.log(isPositiveZero(1)); // false +``` + +## `isPositiveZero` + +#### Signature + +```ts ignore +function isPositiveZero(it: unknown): it is PositiveZero; +``` + +Checks if a given value is positive zero, which is a special numeric value in +JavaScript, distinctly different from it's negative counterpart. Checking for +positive zero involves more than simply `x === +0`, as `+0` is coerced into `0` +in most contexts. + +This function is designed to handle this edge case, and will return `true` only +if the value is **exactly** `+0`, and `false` for anything else. + +This is quite useful for mathematical operations and projects where data +integrity and accuracy are paramount. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is positive zero, `false` otherwise. + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero } from "jsr:@nick/is/number"; + +console.log(isPositiveZero(-0)); // false +console.log(isPositiveZero(0)); // true +console.log(isPositiveZero(-1)); // false +console.log(isPositiveZero(1)); // false +``` + +## `MaybePositiveZero` + +#### Signature + +```ts ignore +export type MaybePositiveZero = Cast; +``` + +Casts a value into a partial positive zero type. If the value is not a number, +it will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero, type MaybePositiveZero } from "jsr:@type/number"; + +let x = 0 as MaybePositiveZero, y = 1; + +if (isPositiveZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 0; // <- No error! (this is the main difference from `PositiveZero`) +``` + +## `PositiveZero` + +#### Signature + +```ts ignore +export type PositiveZero = Cast; +``` + +Casts a value into a positive zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isPositiveZero, type PositiveZero } from "jsr:@type/number"; + +let x = 0 as PositiveZero, y = 1; + +if (isPositiveZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'PositiveZero'. +``` diff --git a/docs/number/positive.md b/docs/number/positive.md new file mode 100644 index 0000000..9abda74 --- /dev/null +++ b/docs/number/positive.md @@ -0,0 +1,166 @@ +# @nick/is/number/positive + +## `isPositive` + +#### Signature + +```ts ignore +function isPositive(it: N): it is Positive; +``` + +Checks if a given value is a positive number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive } from "jsr:@nick/is/integer"; + +console.log(isPositive(0)); // true +console.log(isPositive(1)); // true +console.log(isPositive(-1)); // false +console.log(isPositive(1.5)); // true +console.log(isPositive(NaN)); // false +console.log(isPositive(Infinity)); // true +``` + +## `isPositive` + +#### Signature + +```ts ignore +function isPositive(it: unknown): it is Positive; +``` + +Checks if a given value is a positive number. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if the value is a positive number, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive } from "jsr:@nick/is/integer"; + +console.log(isPositive(0)); // true +console.log(isPositive(1)); // true +console.log(isPositive(-1)); // false +console.log(isPositive(1.5)); // true +console.log(isPositive(NaN)); // false +console.log(isPositive(Infinity)); // true +``` + +## `MaybePositive` + +#### Signature + +```ts ignore +export type MaybePositive = Cast; +``` + +Casts a value into a partial positive type. If the value is not a number, it +will resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `positive` `number` + +#### Examples + +```ts +import { isPositive, type MaybePositive } from "jsr:@type/number"; + +let x = 1 as MaybePositive, y = 0; + +if (isPositive(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Positive`) +``` + +## `Positive` + +#### Signature + +```ts ignore +export type Positive = Cast; +``` + +Casts a value into a positive type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`positive` `number` + +#### Examples + +```ts +import { isPositive, type Positive } from "jsr:@type/number"; + +let x = 1 as Positive, y = 0; + +if (isPositive(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 0; // <- TS2322 Type '0' is not assignable to type 'Positive'. +``` diff --git a/docs/number/types.md b/docs/number/types.md new file mode 100644 index 0000000..3072364 --- /dev/null +++ b/docs/number/types.md @@ -0,0 +1,777 @@ +# @nick/is/number/types + +## `Cast` + +#### Signature + +```ts ignore +export type Cast = Extract & T; +``` + +Casts a value into a specific numeric type. If the value is not a number, it +will resolve to `never`, indicating its incompatibility with the type. + +This is a low-level utility type that primarily serves as an internal helper for +more user-friendly types like [Integer](#integer "Jump to symbol: 'Integer'") +and [Positive](#positive "Jump to symbol: 'Positive'"). Unless you're building +custom numeric types with your own branding, you most likely never directly +handle this type in the wild. + +##### Type Parameters + +- **`N`** +- **`T`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { Cast } from "jsr:@nick/is/number"; + +declare const MY_DOUBLE: unique symbol; +type DOUBLE = Cast; + +let x = 4.3210123210 as DOUBLE; +let y = 3.1415926535 as DOUBLE; + +console.log(x + y); // 7.4626049745 + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'DOUBLE'. +``` + +## `CastInt` + +#### Signature + +```ts ignore +export type CastInt = Extract & T; +``` + +Casts a value into a specific integer type. If the value is not a bigint, it +will resolve to `never`, indicating its incompatibility with the type. + +This is a low-level utility type that primarily serves as an internal helper for +more user-friendly types like +[BigInteger](#biginteger "Jump to symbol: 'BigInteger'") or +[PositiveBigInteger](#positivebiginteger "Jump to symbol: 'PositiveBigInteger'"). +Unless you're building custom numeric types with your own branding, you most +likely will never directly handle this type in the wild. + +##### Type Parameters + +- **`N`** +- **`T`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { CastInt } from "jsr:@nick/is/number"; + +declare const INTEGER: unique symbol; +type INTEGER = CastInt; + +let x = 3n as INTEGER; +let y = 5n as INTEGER; + +console.log(x + y); // 8n +``` + +## `Numeric` + +#### Signature + +```ts ignore +export type Numeric = number | bigint | `${number | bigint}`; +``` + +## `Unwrap` + +#### Signature + +```ts ignore +export type Unwrap = U extends Cast ? [N, T] : [U, never]; +``` + +Unwraps a type that has been cast with [Cast](#cast "Jump to symbol: 'Cast'") +into a tuple of the original value and the specific type it was cast to (or +"branded" with). If the given type was _not_ cast with +[Cast](#cast "Jump to symbol: 'Cast'"), it will resolve to a tuple containing +the original value and `never`, respectively. + +##### Type Parameters + +- **`U`** + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import type { Cast, Unwrap } from "jsr:@nick/is/number"; + +type Int_3 = Cast<3, INTEGER>; + +function unwrap(value: T): Unwrap[0] { + return value as Unwrap[0]; +} +``` + +## `EVEN` + +### Properties + +#### IS_EVEN + +```ts +readonly IS_EVEN: true; +``` + +--- + +## `EVEN_INTEGER` + +## `FINITE` + +### Properties + +#### IS_INFINITE + +```ts +readonly IS_INFINITE: false; +``` + +#### IS_FINITE + +```ts +readonly IS_FINITE: true; +``` + +--- + +## `FLOAT` + +### Properties + +#### IS_FLOAT + +```ts +readonly IS_FLOAT: true; +``` + +--- + +## `FLOAT16` + +##### Extends `FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION: 0.5; +``` + +--- + +## `FLOAT32` + +##### Extends `FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION: 1; +``` + +--- + +## `FLOAT64` + +##### Extends `FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION: 2; +``` + +--- + +## `INFINITE` + +### Properties + +#### IS_FINITE + +```ts +readonly IS_FINITE: false; +``` + +#### IS_INFINITE + +```ts +readonly IS_INFINITE: true; +``` + +--- + +## `INT16` + +##### Extends `INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH: 16; +``` + +--- + +## `INT32` + +##### Extends `INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH: 32; +``` + +--- + +## `INT64` + +##### Extends `INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH: 64; +``` + +--- + +## `INT8` + +##### Extends `INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH: 8; +``` + +--- + +## `INTEGER` + +### Properties + +#### IS_INTEGER + +```ts +readonly IS_INTEGER: true; +``` + +--- + +## `MAYBE_EVEN` + +### Properties + +#### IS_EVEN + +```ts +readonly IS_EVEN?: true; +``` + +--- + +## `MAYBE_EVEN_INTEGER` + +## `MAYBE_FINITE` + +### Properties + +#### IS_INFINITE + +```ts +readonly IS_INFINITE?: false; +``` + +#### IS_FINITE + +```ts +readonly IS_FINITE?: true; +``` + +--- + +## `MAYBE_FLOAT` + +### Properties + +#### IS_FLOAT + +```ts +readonly IS_FLOAT?: true; +``` + +--- + +## `MAYBE_FLOAT16` + +##### Extends `MAYBE_FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION?: 0.5; +``` + +--- + +## `MAYBE_FLOAT32` + +##### Extends `MAYBE_FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION?: 1; +``` + +--- + +## `MAYBE_FLOAT64` + +##### Extends `MAYBE_FLOAT` + +### Properties + +#### PRECISION + +```ts +readonly PRECISION?: 2; +``` + +--- + +## `MAYBE_INFINITE` + +### Properties + +#### IS_FINITE + +```ts +readonly IS_FINITE?: false; +``` + +#### IS_INFINITE + +```ts +readonly IS_INFINITE?: true; +``` + +--- + +## `MAYBE_INT16` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH?: 16; +``` + +--- + +## `MAYBE_INT32` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH?: 32; +``` + +--- + +## `MAYBE_INT64` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH?: 64; +``` + +--- + +## `MAYBE_INT8` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### BIT_LENGTH + +```ts +readonly BIT_LENGTH?: 8; +``` + +--- + +## `MAYBE_INTEGER` + +### Properties + +#### IS_INTEGER + +```ts +readonly IS_INTEGER?: true; +``` + +--- + +## `MAYBE_NAN` + +### Properties + +#### IS_NAN + +```ts +readonly IS_NAN?: true; +``` + +--- + +## `MAYBE_NEGATIVE` + +### Properties + +#### IS_POSITIVE + +```ts +readonly IS_POSITIVE?: false; +``` + +#### IS_NEGATIVE + +```ts +readonly IS_NEGATIVE?: true; +``` + +--- + +## `MAYBE_NEGATIVE_FINITE` + +## `MAYBE_NEGATIVE_INFINITY` + +## `MAYBE_NEGATIVE_INTEGER` + +## `MAYBE_NEGATIVE_NON_ZERO_FINITE` + +## `MAYBE_NEGATIVE_NON_ZERO_INTEGER` + +## `MAYBE_NEGATIVE_ZERO` + +## `MAYBE_NON_ZERO` + +### Properties + +#### IS_ZERO + +```ts +readonly IS_ZERO?: false; +``` + +#### IS_NON_ZERO + +```ts +readonly IS_NON_ZERO?: true; +``` + +--- + +## `MAYBE_NON_ZERO_FINITE` + +## `MAYBE_NON_ZERO_INTEGER` + +## `MAYBE_ODD` + +### Properties + +#### IS_ODD + +```ts +readonly IS_ODD?: true; +``` + +--- + +## `MAYBE_ODD_INTEGER` + +## `MAYBE_POSITIVE` + +### Properties + +#### IS_NEGATIVE + +```ts +readonly IS_NEGATIVE?: false; +``` + +#### IS_POSITIVE + +```ts +readonly IS_POSITIVE?: true; +``` + +--- + +## `MAYBE_POSITIVE_FINITE` + +## `MAYBE_POSITIVE_INFINITY` + +## `MAYBE_POSITIVE_INTEGER` + +## `MAYBE_POSITIVE_NON_ZERO_FINITE` + +## `MAYBE_POSITIVE_NON_ZERO_INTEGER` + +## `MAYBE_POSITIVE_ODD_INTEGER` + +## `MAYBE_POSITIVE_ZERO` + +## `MAYBE_UINT16` + +## `MAYBE_UINT32` + +## `MAYBE_UINT64` + +## `MAYBE_UINT8` + +## `MAYBE_UNSIGNED` + +##### Extends `MAYBE_INTEGER` + +### Properties + +#### IS_UNSIGNED + +```ts +readonly IS_UNSIGNED?: true; +``` + +--- + +## `MAYBE_ZERO` + +### Properties + +#### IS_NON_ZERO + +```ts +readonly IS_NON_ZERO?: false; +``` + +#### IS_ZERO + +```ts +readonly IS_ZERO?: true; +``` + +--- + +## `NAN` + +### Properties + +#### IS_NAN + +```ts +readonly IS_NAN: true; +``` + +--- + +## `NEGATIVE` + +### Properties + +#### IS_POSITIVE + +```ts +readonly IS_POSITIVE: false; +``` + +#### IS_NEGATIVE + +```ts +readonly IS_NEGATIVE: true; +``` + +--- + +## `NEGATIVE_FINITE` + +## `NEGATIVE_INFINITY` + +## `NEGATIVE_INTEGER` + +## `NEGATIVE_NON_ZERO_FINITE` + +## `NEGATIVE_NON_ZERO_INTEGER` + +## `NEGATIVE_ZERO` + +## `NON_ZERO` + +### Properties + +#### IS_ZERO + +```ts +readonly IS_ZERO: false; +``` + +#### IS_NON_ZERO + +```ts +readonly IS_NON_ZERO: true; +``` + +--- + +## `NON_ZERO_FINITE` + +## `NON_ZERO_INTEGER` + +## `ODD` + +### Properties + +#### IS_ODD + +```ts +readonly IS_ODD: true; +``` + +--- + +## `ODD_INTEGER` + +## `POSITIVE` + +### Properties + +#### IS_NEGATIVE + +```ts +readonly IS_NEGATIVE: false; +``` + +#### IS_POSITIVE + +```ts +readonly IS_POSITIVE: true; +``` + +--- + +## `POSITIVE_FINITE` + +## `POSITIVE_INFINITY` + +## `POSITIVE_INTEGER` + +## `POSITIVE_NON_ZERO_FINITE` + +## `POSITIVE_NON_ZERO_INTEGER` + +## `POSITIVE_ODD_INTEGER` + +## `POSITIVE_ZERO` + +## `UINT16` + +## `UINT32` + +## `UINT64` + +## `UINT8` + +## `UNSIGNED` + +##### Extends `INTEGER` + +### Properties + +#### IS_UNSIGNED + +```ts +readonly IS_UNSIGNED: true; +``` + +--- + +## `ZERO` + +### Properties + +#### IS_NON_ZERO + +```ts +readonly IS_NON_ZERO: false; +``` + +#### IS_ZERO + +```ts +readonly IS_ZERO: true; +``` + +--- diff --git a/docs/number/uint16.md b/docs/number/uint16.md new file mode 100644 index 0000000..2e75baf --- /dev/null +++ b/docs/number/uint16.md @@ -0,0 +1,173 @@ +# @nick/is/number/uint16 + +## `isUint16` + +#### Signature + +```ts ignore +function isUint16(it: N): it is Uint16; +``` + +Checks if a given value is an unsigned 16-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `isUint16` + +#### Signature + +```ts ignore +function isUint16(it: unknown): it is Uint16; +``` + +Checks if a given value is an unsigned 16-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 16-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `MaybeUint16` + +#### Signature + +```ts ignore +export type MaybeUint16 = Cast; +``` + +Casts a value into a partial unsigned 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` + +## `Uint16` + +#### Signature + +```ts ignore +export type Uint16 = Cast; +``` + +Casts a value into an unsigned 16-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint16, type MaybeUint16, type Uint16 } from "@nick/is/number"; + +let value = 1 as Uint16; + +const setValue = (newValue: MaybeUint16) => { + if (isUint16(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint16'. +``` diff --git a/docs/number/uint32.md b/docs/number/uint32.md new file mode 100644 index 0000000..466e1b5 --- /dev/null +++ b/docs/number/uint32.md @@ -0,0 +1,173 @@ +# @nick/is/number/uint32 + +## `isUint32` + +#### Signature + +```ts ignore +function isUint32(it: N): it is Uint32; +``` + +Checks if a given value is an unsigned 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `isUint32` + +#### Signature + +```ts ignore +function isUint32(it: unknown): it is Uint32; +``` + +Checks if a given value is an unsigned 32-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 32-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `MaybeUint32` + +#### Signature + +```ts ignore +export type MaybeUint32 = Cast; +``` + +Casts a value into a partial unsigned 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` + +## `Uint32` + +#### Signature + +```ts ignore +export type Uint32 = Cast; +``` + +Casts a value into an unsigned 32-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint32, type MaybeUint32, type Uint32 } from "@nick/is/number"; + +let value = 1 as Uint32; + +const setValue = (newValue: MaybeUint32) => { + if (isUint32(newValue)) value = newValue; +}; + +setValue(0xFFFF); // <- No error! + +// This will raise a TypeScript compiler error: +value = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint32'. +``` diff --git a/docs/number/uint8.md b/docs/number/uint8.md new file mode 100644 index 0000000..72d2bb6 --- /dev/null +++ b/docs/number/uint8.md @@ -0,0 +1,162 @@ +# @nick/is/number/uint8 + +## `isUint8` + +#### Signature + +```ts ignore +function isUint8(it: N): it is Uint8; +``` + +Checks if a given value is an unsigned 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint8 } from "jsr:@nick/is/uint8"; + +isUint8(1); // true +isUint8(128); // true +isUint8(0xFF); // true +isUint8(-1); // false +isUint8(420); // false +``` + +## `isUint8` + +#### Signature + +```ts ignore +function isUint8(it: unknown): it is Uint8; +``` + +Checks if a given value is an unsigned 8-bit integer. + +##### Parameters + +| Name | Info | +| :------- | :------------------ | +| **`it`** | The value to check. | + +##### Returns + +`true` if `it` is an unsigned 8-bit integer, `false` otherwise. + +###### Category + +`Numbers` + +###### Tags + +`number` `unsigned` `integer` + +#### Examples + +```ts +import { isUint8 } from "jsr:@nick/is/uint8"; + +isUint8(1); // true +isUint8(128); // true +isUint8(0xFF); // true +isUint8(-1); // false +isUint8(420); // false +``` + +## `MaybeUint8` + +#### Signature + +```ts ignore +export type MaybeUint8 = Cast; +``` + +Casts a value into a partial unsigned 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`maybe` `unsigned` `integer` + +#### Examples + +```ts +import { isUint8, type MaybeUint8 } from "@nick/is/uint8"; + +let i = 1 as MaybeUint8, y = 0; + +if (isUint8(i)) { + console.log(i); +} else { + console.log(y); +} + +y = 1; // <- No error! (this is the main difference from `Uint8`) +``` + +## `Uint8` + +#### Signature + +```ts ignore +export type Uint8 = Cast; +``` + +Casts a value into an unsigned 8-bit integer type. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Categories + +`Numbers` `Types` + +###### Tags + +`unsigned` `integer` + +#### Examples + +```ts +import { isUint8, type Uint8 } from "@nick/is/uint8"; + +let i = 1 as Uint8, y = 0; + +if (isUint8(i)) { + console.log(i); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +i = -1; // <- TS2322 Type '-1' is not assignable to type 'Uint8'. +``` diff --git a/docs/number/zero.md b/docs/number/zero.md new file mode 100644 index 0000000..e95f31c --- /dev/null +++ b/docs/number/zero.md @@ -0,0 +1,116 @@ +# @nick/is/number/zero + +## `isZero` + +#### Signature + +```ts ignore +function isZero(it: N): it is Zero; +``` + +Checks if a given value is a zero number. This includes both positive and +negative zero. It also supports numbers and numeric strings. + +- To check exclusively for `-0`, use + [isNegativeZero](#isnegativezero "Jump to symbol: 'isNegativeZero'") instead. +- To check exclusively for `+0` (meaning zero, but **not** negative zero), use + [isPositiveZero](#ispositivezero "Jump to symbol: 'isPositiveZero'") instead. + +###### Category + +`Numbers` + +## `isZero` + +#### Signature + +```ts ignore +function isZero(it: unknown): it is Zero; +``` + +Checks if a given value is a zero number. This includes both positive and +negative zero. It also supports numbers and numeric strings. + +- To check exclusively for `-0`, use + [isNegativeZero](#isnegativezero "Jump to symbol: 'isNegativeZero'") instead. +- To check exclusively for `+0` (meaning zero, but **not** negative zero), use + [isPositiveZero](#ispositivezero "Jump to symbol: 'isPositiveZero'") instead. + +###### Category + +`Numbers` + +## `MaybeZero` + +#### Signature + +```ts ignore +export type MaybeZero = Cast; +``` + +Casts a value into a partial zero type. If the value is not a number, it will +resolve to `never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isZero, type MaybeZero } from "jsr:@type/number"; + +let x = 0 as MaybeZero, y = 1; + +if (isZero(x)) { + console.log(x); +} else { + console.log(y); +} + +y = 0; // <- No error! (this is the main difference from `Zero`) +``` + +## `Zero` + +#### Signature + +```ts ignore +export type Zero = Cast; +``` + +Casts a value into a zero type. If the value is not a number, it will resolve to +`never`. + +##### Type Parameters + +- **`N`** (default: `number`) + +--- + +###### Category + +`Numbers` + +#### Examples + +```ts +import { isZero, type Zero } from "jsr:@type/number/zero"; + +let x = 0 as Zero, y = 1; + +if (isZero(x)) { + console.log(x); +} else { + console.log(y); +} + +// This will raise a TypeScript compiler error: +x = 1; // <- TS2322 Type '1' is not assignable to type 'Zero'. +``` diff --git a/docs/type/any-or-never.md b/docs/type/any-or-never.md new file mode 100644 index 0000000..f04168e --- /dev/null +++ b/docs/type/any-or-never.md @@ -0,0 +1,79 @@ +# @nick/is/type/any-or-never + +## `IsAnyOrNever` + +#### Signature + +```ts ignore +export type IsAnyOrNever = IsNever< + T, + True, + IsAny +>; +``` + +Check if the type [`T`](#t "Jump to symbol: 'T'") is either `any` or `never`, +returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. + +This type guard is useful when you need to check if a value can be of any type +_or_ if it is unreachable. If you only need to check if a type is `any`, use the +[`IsAny`](#isany "Jump to symbol: 'IsAny'") type guard instead. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsAnyOrNever } from "@nick/is/type/any-or-never"; + +type A = IsAnyOrNever; // true +type B = IsAnyOrNever; // true +type C = IsAnyOrNever; // false +``` + +## `OmitAnyOrNever` + +#### Signature + +```ts ignore +export type OmitAnyOrNever = T extends object ? { + [K in [object Object]]: + Deep extends true ? OmitAnyOrNever : T[K] + } : T; +``` + +Omit properties from an object type where the value is `any` or `never`. This +relies on the [`IsAnyOrNever`](#isanyornever "Jump to symbol: 'IsAnyOrNever'") +utility type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitAnyOrNever } from "@nick/is/type"; + +type A = { a: string; b: any; c: number; d: never }; +type B = OmitAnyOrNever; +// ^? type B = { a: string; c: number } +``` diff --git a/docs/type/any-or-unknown-or-never.md b/docs/type/any-or-unknown-or-never.md new file mode 100644 index 0000000..9b40440 --- /dev/null +++ b/docs/type/any-or-unknown-or-never.md @@ -0,0 +1,84 @@ +# @nick/is/type/any-or-unknown-or-never + +## `IsAnyOrUnknownOrNever` + +#### Signature + +```ts ignore +export type IsAnyOrUnknownOrNever = IsAny< + T, + True, + IsUnknownOrNever +>; +``` + +Resolves to [`True`](#true "Jump to symbol: 'True'") if `A` is `any`, `unknown`, +or `never`. Otherwise, it resolves to +[`False`](#false "Jump to symbol: 'False'"). + +This composite type combines [`IsAny`](#isany "Jump to symbol: 'IsAny'"), +[`IsNever`](#isnever "Jump to symbol: 'IsNever'"), and +[`IsUnknown`](#isunknown "Jump to symbol: 'IsUnknown'") into a single type-level +predicate. It's useful when creating your own custom type-level predicates, as +its usually a good idea to first check the input type is **not** `any`, +`unknown`, or `never` before moving on to the assignability of the type you're +actually interested in. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +#### Examples + +```ts +import type { IsAnyOrUnknownOrNever } from "@nick/is/type"; + +type A = IsAnyOrUnknownOrNever; // true +type B = IsAnyOrUnknownOrNever; // true +type C = IsAnyOrUnknownOrNever; // true + +type D = IsAnyOrUnknownOrNever; // false +type E = IsAnyOrUnknownOrNever<"hello">; // false +type F = IsAnyOrUnknownOrNever<1>; // false +``` + +## `OmitAnyUnknownNever` + +#### Signature + +```ts ignore +export type OmitAnyUnknownNever = U extends infer T extends object ? { + [K in [object Object]]: + Deep extends true ? OmitAnyUnknownNever : T[K] + } : IsAnyOrUnknownOrNever; +``` + +Omit properties from an object type where the value is `any`, `unknown`, or +`never`. This relies on the +[`IsAnyOrUnknownOrNever`](#isanyorunknownornever "Jump to symbol: 'IsAnyOrUnknownOrNever'") +utility type. + +##### Type Parameters + +- **`U`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitAnyUnknownNever } from "@nick/is/type"; + +type A = { a: string; b: any; c: number; d: unknown; e: ""; f: never }; +type B = OmitAnyUnknownNever; +// ^? type B = { a: string; c: number; e: "" } +``` diff --git a/docs/type/any-or-unknown.md b/docs/type/any-or-unknown.md new file mode 100644 index 0000000..fb6cce7 --- /dev/null +++ b/docs/type/any-or-unknown.md @@ -0,0 +1,84 @@ +# @nick/is/type/any-or-unknown + +## `IsAnyOrUnknownOrNever` + +#### Signature + +```ts ignore +export type IsAnyOrUnknownOrNever = IsAny< + T, + True, + IsUnknownOrNever +>; +``` + +Resolves to [`True`](#true "Jump to symbol: 'True'") if `A` is `any`, `unknown`, +or `never`. Otherwise, it resolves to +[`False`](#false "Jump to symbol: 'False'"). + +This composite type combines [`IsAny`](#isany "Jump to symbol: 'IsAny'"), +[`IsNever`](#isnever "Jump to symbol: 'IsNever'"), and +[`IsUnknown`](#isunknown "Jump to symbol: 'IsUnknown'") into a single type-level +predicate. It's useful when creating your own custom type-level predicates, as +its usually a good idea to first check the input type is **not** `any`, +`unknown`, or `never` before moving on to the assignability of the type you're +actually interested in. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +#### Examples + +```ts +import type { IsAnyOrUnknownOrNever } from "@nick/is/type"; + +type A = IsAnyOrUnknownOrNever; // true +type B = IsAnyOrUnknownOrNever; // true +type C = IsAnyOrUnknownOrNever; // true + +type D = IsAnyOrUnknownOrNever; // false +type E = IsAnyOrUnknownOrNever<"hello">; // false +type F = IsAnyOrUnknownOrNever<1>; // false +``` + +## `OmitAnyUnknownNever` + +#### Signature + +```ts ignore +export type OmitAnyUnknownNever = U extends infer T extends object ? { + [K in [object Object]]: + Deep extends true ? OmitAnyUnknownNever : T[K] + } : IsAnyOrUnknownOrNever; +``` + +Omit properties from an object type where the value is `any`, `unknown`, or +`never`. This relies on the +[`IsAnyOrUnknownOrNever`](#isanyorunknownornever "Jump to symbol: 'IsAnyOrUnknownOrNever'") +utility type. + +##### Type Parameters + +- **`U`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitAnyUnknownNever } from "@nick/is/type"; + +type A = { a: string; b: any; c: number; d: unknown; e: ""; f: never }; +type B = OmitAnyUnknownNever; +// ^? type B = { a: string; c: number; e: "" } +``` diff --git a/docs/type/any.md b/docs/type/any.md new file mode 100644 index 0000000..c42a14b --- /dev/null +++ b/docs/type/any.md @@ -0,0 +1,113 @@ +# @nick/is/type/any + +## `IsAny` + +#### Signature + +```ts ignore +export type IsAny = IsBoolean< + A extends never ? true : false, + True, + False +>; +``` + +Checks if the type [`A`](#a "Jump to symbol: 'A'") is the `any` type, and +nothing else. This is useful for creating your own type guards, conditional +types, and other utilities where you need to determine whether or not a specific +type or type parameter is the `any` type. + +This type will resolve to [`True`](#true "Jump to symbol: 'True'") (default +`true`) if `A` is `any`. Otherwise, it resolves to the +[`False`](#false "Jump to symbol: 'False'") parameter (default `false`). This +allows you to create complex/nested conditional types with a minimal amount of +boilerplate. + +##### Type Parameters + +- **`A`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsAny } from "@nick/is/type"; + +type A = IsAny; // true +type B = IsAny; // "not any" +``` + +```ts +import type { IsAny } from "@nick/is/type"; + +type IsNotAny = IsAny; + +type A = IsNotAny; // never +type B = IsNotAny; // unknown +type C = IsNotAny; // never +type D = IsNotAny; // any[] +type E = IsNotAny; // string +``` + +```ts +import type { IsAny } from "@nick/is/type"; + +type OmitAny = U extends + infer T extends U & object ? { + [K in keyof T as IsAny]: Deep extends true + ? OmitAny + : T[K]; + } + : IsAny; + +declare const userData: OmitAny<{ + id: string; + name: string; + age: number; + data: any; // <-- this will be omitted +}>; + +userData; +// ^? const userData: { id: string; name: string; age: number } +``` + +## `OmitAny` + +#### Signature + +```ts ignore +export type OmitAny = T extends object ? { + [K in [object Object]]: Deep extends true ? OmitAny : T[K] + } : T; +``` + +Omit properties from an object type where the value is `any`. This relies on the +[`IsAny`](#isany "Jump to symbol: 'IsAny'") utility type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitAny } from "@nick/is/type"; + +type A = { a: string; b: any; c: number }; +type B = OmitAny; +// ^? type B = { a: string; c: number } +``` diff --git a/docs/type/array.md b/docs/type/array.md new file mode 100644 index 0000000..02c6145 --- /dev/null +++ b/docs/type/array.md @@ -0,0 +1,88 @@ +# @nick/is/type/array + +## `IsArray` + +#### Signature + +```ts ignore +export type IsArray = IsAnyOrUnknownOrNever< + T, + False, + T extends readonly unknown[] ? True : False +>; +``` + +Resolves to [`True`](#true "Jump to symbol: 'True'") if +[`A`](#a "Jump to symbol: 'A'") is an array, which is a list of variable length +with values that can be of any type. This check **does** include tuples like +`[1, 2, 3]`, standard arrays like `string[]`, and also generic arrays like +`Array` in what it considers valid. Any other type resolves to +[`False`](#false "Jump to symbol: 'False'"). + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsArray } from "@nick/is/type"; + +type A = IsArray<[1, 2, 3]>; // true +type B = IsArray<[unknown, unkown, unknown, unknown, unknown]>; // true +type C = IsArray; // true +type D = IsArray>; // true +type E = IsArray>; // true +type F = IsArray; // true + +type G = IsArray; // false +type H = IsArray; // false +``` + +## `IsNonTupleArray` + +#### Signature + +```ts ignore +export type IsNonTupleArray = IsArray< + T, + IsTuple, + False +>; +``` + +Resolves to [`True`](#true "Jump to symbol: 'True'") if +[`A`](#a "Jump to symbol: 'A'") is an array, but **not** a tuple. This check +includes standard arrays like `string[]` and generic arrays like +`Array`, but **excludes** tuples like `[1, 2, 3]`. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsNonTupleArray } from "@nick/is/type"; + +type A = IsNonTupleArray<[1, 2, 3]>; // false +type B = IsNonTupleArray<[unknown, unkown, unknown]>; // false +type C = IsNonTupleArray; // true +type D = IsNonTupleArray>; // true +``` diff --git a/docs/type/assertion.md b/docs/type/assertion.md new file mode 100644 index 0000000..bed6dde --- /dev/null +++ b/docs/type/assertion.md @@ -0,0 +1,35 @@ +# @nick/is/type/assertion + +## `Assertion` + +#### Signature + +```ts ignore +export type Assertion< + Type extends Base = any, + Base = unknown, + Args extends readonly unknown[] = readonly any[], +> = Expand<(it: Base, ...args: Args) => asserts it is Type>; +``` + +Represents an assertion function that checks if a given value of the base type +`Base` is also of the derived type `Type`. If the value is not of the derived +type, it will throw an error. + +##### Type Parameters + +- **`Type`** extends `Base` (default: `any`) +- **`Base`** (default: `unknown`) +- **`Args`** extends `readonly unknown[]` (default: `readonly any[]`) + +--- + +#### Examples + +```ts +const assertString: Assertion = (it: unknown): asserts it is string => { + if (typeof it !== "string") { + throw new TypeError("Expected a string"); + } +}; +``` diff --git a/docs/type/boolean.md b/docs/type/boolean.md new file mode 100644 index 0000000..3749689 --- /dev/null +++ b/docs/type/boolean.md @@ -0,0 +1,115 @@ +# @nick/is/type/boolean + +## `IsBoolean` + +#### Signature + +```ts ignore +export type IsBoolean = [T] extends [boolean] + ? [boolean] extends [T] ? True : False + : False; +``` + +Checks if the type [`T`](#t "Jump to symbol: 'T'") is the generic type +`boolean`, returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. + +This predicate is not satisfied by just `true` or `false`; the type must be a +union of both (`true | false`, which is what the `boolean` type actually +represents) to result in a positive match. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Categories + +`Types` `Boolean` + +#### Examples + +```ts +import type { IsBoolean } from "@nick/is/type/boolean"; + +type A = IsBoolean; // false +type B = IsBoolean; // false +type C = IsBoolean; // false + +type Y = IsBoolean; // true +type Z = IsBoolean; // true +``` + +## `IsFalse` + +#### Signature + +```ts ignore +export type IsFalse = [T, false] extends + [false, T] ? True : False; +``` + +Checks if the type [`T`](#t "Jump to symbol: 'T'") is specifically `false`, +returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Categories + +`Types` `Boolean` + +#### Examples + +```ts +import type { IsFalse } from "@nick/is/type/boolean"; + +type A = IsFalse; // false +type B = IsFalse; // true +type C = IsFalse; // false +``` + +## `IsTrue` + +#### Signature + +```ts ignore +export type IsTrue = [T, true] extends [true, T] + ? True + : False; +``` + +Checks if the type [`T`](#t "Jump to symbol: 'T'") is specifically `true`, +returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Categories + +`Types` `Boolean` + +#### Examples + +```ts +import type { IsTrue } from "@nick/is/type/boolean"; + +type A = IsTrue; // true +type B = IsTrue; // false +type C = IsTrue; // false +``` diff --git a/docs/type/exact.md b/docs/type/exact.md new file mode 100644 index 0000000..b960923 --- /dev/null +++ b/docs/type/exact.md @@ -0,0 +1,59 @@ +# @nick/is/type/exact + +## `IsExact` + +#### Signature + +```ts ignore +export type IsExact = Matches< + Eq>, + Eq>, + True, + False +>; +``` + +Type-level predicate to check if [`T`](#t "Jump to symbol: 'T'") and +[`U`](#u "Jump to symbol: 'U'") are exactly the same type in terms of their +structural assignability. If the types are an exact match, it will resolve to +[`True`](#true "Jump to symbol: 'True'") (default: true). If not, it will +resolve to [`False`](#false "Jump to symbol: 'False'") (default: false). + +You can override the `True` and `False` type parameters to customize the +behavior of this type predicate, and effectively create a type-level ternery +operation. Be mindful that while you _can_ create nested conditional type checks +with this, it is usually not recommended to do so (for the same reasons why it's +discouraged to do so with a runtime ternary operator). + +This is a strict comparison that leverages TypeScript's internal semantics +surrounding type variance and assignability, and is not just a simple +`T +extends U` check. + +##### Type Parameters + +- **`T`** +- **`U`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +#### Examples + +```ts +import type { IsExact } from "@nick/is/type/exact"; + +type A = IsExact<"hello", "hello">; // true +type B = IsExact<{ a: string | null }, { a: string | null }>; // true +type C = IsExact; // true +type D = IsExact; // true + +type E = IsExact; // false +type F = IsExact; // false +type G = IsExact<{ a: string | null }, { a: string }>; // false +type H = IsExact<{ a: string | null }, { a: string | undefined }>; // false +type I = IsExact<{ a: string; b?: number }, { a: string; b: number }>; // false +type J = IsExact<{ a: void }, { a: undefined }>; // false +type K = T.IsExact<{ a: boolean }, { a: any }>; // false +``` diff --git a/docs/type/expect.md b/docs/type/expect.md new file mode 100644 index 0000000..1f8f5b1 --- /dev/null +++ b/docs/type/expect.md @@ -0,0 +1,72 @@ +# @nick/is/type/expect + +## `expectType` + +#### Signature + +```ts ignore +function expectType(value: T): void; +``` + +A no-op function that is used for explicit type checking in TypeScript. + +This function is a generic function that takes a single type parameter `T` and a +single argument of type `T`. The function does not perform any operations at +runtime, but it is used to check that the type of the argument passed to it is a +match for type `T`. This is useful for testing purposes. + +##### Parameters + +| Name | Info | +| :---------- | :------------------------------- | +| **`value`** | THe value to assert the type of. | + +##### Returns + +Nothing. + +###### Category + +`Testing` + +#### Examples + +```ts +import { expectType } from "@nick/is/type/expect"; + +let result: string | number = "hello world".toString(); + +// This will raise a type error if `result` is not a `string` +expectType(result); + +const literal = "hello world"; + +// This will raise a type error if `literal` is not a string literal +expectType<"hello world">(literal); +``` + +## `ExpectType` + +#### Signature + +```ts ignore +export type ExpectType = TActual; +``` + +Type-level equivalent to the +[`expectType`](#expecttype "Jump to symbol: 'expectType'") function. + +This type alias accepts 2 type parameters: `TExpected` and `TActual`. If the +type of `TActual` is not assignable to `TExpected`, it will raise a compiler +error indicating as much. This is useful for testing purposes. + +##### Type Parameters + +- **`TExpected`** +- **`TActual`** extends `TExpected` + +--- + +###### Category + +`Types` diff --git a/docs/type/index-signature.md b/docs/type/index-signature.md new file mode 100644 index 0000000..ef7dfa9 --- /dev/null +++ b/docs/type/index-signature.md @@ -0,0 +1,104 @@ +# @nick/is/type/index-signature + +## `IsIndexSignature` + +#### Signature + +```ts ignore +export type IsIndexSignature = K extends + PropertyKey ? {} extends Record ? True : False : False; +``` + +If [`K`](#k "Jump to symbol: 'K'") is a valid index signature of an +object-literal type, this resolves to [`True`](#true "Jump to symbol: 'True'"). +Otherwise, it resolves to [`False`](#false "Jump to symbol: 'False'"). + +Index signatures are not like literal keys of an object. They do share the same +supertypes (either a string, symbol, or number), but instead of them specifying +a single property's key on the object, they define _ranges_ of keys that an +object can accept, based on their type. + +Visually, they are surrounded with square brackets, similar to computed +properties. Inside of the square brackets, the index signature's label and type +are defined. + +##### Type Parameters + +- **`K`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +#### Signature + +```ts ignore +type ArrayLike = { + readonly length: number; // <- standard property + [index: number]: T | undefined; // <- index signature +}; + +// using `IsIndexSignature` to filter out index signatures +type WithoutIndexSignature = { + [K in keyof T as IsIndexSignature]: T[K]; +}; + +type IsolateIndexSignature = { + [K in keyof T as IsIndexSignature]: T[K]; +}; + +type A = WithoutIndexSignature>; +// ^? type A = { readonly length: number } + +type B = IsolateIndexSignature>; +// ^? type B = { readonly [index: number]: string | undefined } +``` + +This type is often used for mostly cosmetic purposes, as index signatures tend +to make a type look less clean; however, it also serves a practical purpose, +allowing you to make a type more specific and restrict the keys that can be used +with it to only those that are explicitly defined. + +## `OmitIndexSignature` + +#### Signature + +```ts ignore +export type OmitIndexSignature = { + [K in [object Object]]: T[K] + }; +``` + +Omit generic index signatures from an object type. This is useful for filtering +out index signatures that are too broad, allowing you to clean up a type so it +only contains literal properties. + +This relies on the +[`IsIndexSignature`](#isindexsignature "Jump to symbol: 'IsIndexSignature'") +utility type. + +##### Type Parameters + +- **`T`** + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitIndexSignature } from "@nick/is/type"; + +type A = { 0: "foo"; length: 1; [y: number]: string }; +type B = OmitIndexSignature; +// ^? type B = { 0: "foo"; length: 1 } +``` diff --git a/docs/type/literal.md b/docs/type/literal.md new file mode 100644 index 0000000..d082440 --- /dev/null +++ b/docs/type/literal.md @@ -0,0 +1,51 @@ +# @nick/is/type/literal + +## `IsLiteral` + +#### Signature + +```ts ignore +export type IsLiteral = [T] extends [never] + ? False + : [T] extends [null] ? True + : [T] extends [undefined] ? True + : [T] extends [boolean] ? IsBoolean + : [T] extends [number] ? number extends T ? False : True + : [T] extends [string] ? string extends T ? False : True + : [T] extends [bigint] ? bigint extends T ? False : True + : [T] extends [symbol] ? symbol extends T ? False : True + : [T] extends [Record] + ? Record extends T ? False : True + : T extends readonly [] | readonly [any, ...readonly any[]] + ? number extends T["length"] ? False : True + : [T] extends [object] ? object extends T ? False : True + : False; +``` + +If the given type [`T`](#t "Jump to symbol: 'T'") is a literal value (meaning a +string, number, boolean, bigint, symbol, object literal, or a tuple), this type +will resolve to the [`True`](#true "Jump to symbol: 'True'") type parameter, +which has a default value of `true`. Otherwise it resolves to the +[`False`](#false "Jump to symbol: 'False'") type parameter, which has a default +value of `false`. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsLiteral } from "@nick/is/type"; + +type A1 = IsLiteral<"foo">; // true +type A2 = IsLiteral; // false +``` diff --git a/docs/type/mod.md b/docs/type/mod.md new file mode 100644 index 0000000..3c4a86f --- /dev/null +++ b/docs/type/mod.md @@ -0,0 +1,1374 @@ +# @nick/is/type/mod + +## `expectType` + +#### Signature + +```ts ignore +function expectType(value: T): void; +``` + +A no-op function that is used for explicit type checking in TypeScript. + +This function is a generic function that takes a single type parameter `T` and a +single argument of type `T`. The function does not perform any operations at +runtime, but it is used to check that the type of the argument passed to it is a +match for type `T`. This is useful for testing purposes. + +##### Parameters + +| Name | Info | +| :---------- | :------------------------------- | +| **`value`** | THe value to assert the type of. | + +##### Returns + +Nothing. + +###### Category + +`Testing` + +#### Examples + +```ts +import { expectType } from "@nick/is/type/expect"; + +let result: string | number = "hello world".toString(); + +// This will raise a type error if `result` is not a `string` +expectType(result); + +const literal = "hello world"; + +// This will raise a type error if `literal` is not a string literal +expectType<"hello world">(literal); +``` + +## `Assertion` + +#### Signature + +```ts ignore +export type Assertion< + Type extends Base = any, + Base = unknown, + Args extends readonly unknown[] = readonly any[], +> = Expand<(it: Base, ...args: Args) => asserts it is Type>; +``` + +Represents an assertion function that checks if a given value of the base type +`Base` is also of the derived type `Type`. If the value is not of the derived +type, it will throw an error. + +##### Type Parameters + +- **`Type`** extends `Base` (default: `any`) +- **`Base`** (default: `unknown`) +- **`Args`** extends `readonly unknown[]` (default: `readonly any[]`) + +--- + +#### Examples + +```ts +const assertString: Assertion = (it: unknown): asserts it is string => { + if (typeof it !== "string") { + throw new TypeError("Expected a string"); + } +}; +``` + +## `ExpectType` + +#### Signature + +```ts ignore +export type ExpectType = TActual; +``` + +Type-level equivalent to the +[`expectType`](#expecttype "Jump to symbol: 'expectType'") function. + +This type alias accepts 2 type parameters: `TExpected` and `TActual`. If the +type of `TActual` is not assignable to `TExpected`, it will raise a compiler +error indicating as much. This is useful for testing purposes. + +##### Type Parameters + +- **`TExpected`** +- **`TActual`** extends `TExpected` + +--- + +###### Category + +`Types` + +## `IsAny` + +#### Signature + +```ts ignore +export type IsAny = IsBoolean< + A extends never ? true : false, + True, + False +>; +``` + +Checks if the type [`A`](#a "Jump to symbol: 'A'") is the `any` type, and +nothing else. This is useful for creating your own type guards, conditional +types, and other utilities where you need to determine whether or not a specific +type or type parameter is the `any` type. + +This type will resolve to [`True`](#true "Jump to symbol: 'True'") (default +`true`) if `A` is `any`. Otherwise, it resolves to the +[`False`](#false "Jump to symbol: 'False'") parameter (default `false`). This +allows you to create complex/nested conditional types with a minimal amount of +boilerplate. + +##### Type Parameters + +- **`A`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsAny } from "@nick/is/type"; + +type A = IsAny; // true +type B = IsAny; // "not any" +``` + +```ts +import type { IsAny } from "@nick/is/type"; + +type IsNotAny = IsAny; + +type A = IsNotAny; // never +type B = IsNotAny; // unknown +type C = IsNotAny; // never +type D = IsNotAny; // any[] +type E = IsNotAny; // string +``` + +```ts +import type { IsAny } from "@nick/is/type"; + +type OmitAny = U extends + infer T extends U & object ? { + [K in keyof T as IsAny]: Deep extends true + ? OmitAny + : T[K]; + } + : IsAny; + +declare const userData: OmitAny<{ + id: string; + name: string; + age: number; + data: any; // <-- this will be omitted +}>; + +userData; +// ^? const userData: { id: string; name: string; age: number } +``` + +## `IsAnyOrNever` + +#### Signature + +```ts ignore +export type IsAnyOrNever = IsNever< + T, + True, + IsAny +>; +``` + +Check if the type [`T`](#t "Jump to symbol: 'T'") is either `any` or `never`, +returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. + +This type guard is useful when you need to check if a value can be of any type +_or_ if it is unreachable. If you only need to check if a type is `any`, use the +[`IsAny`](#isany "Jump to symbol: 'IsAny'") type guard instead. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsAnyOrNever } from "@nick/is/type/any-or-never"; + +type A = IsAnyOrNever; // true +type B = IsAnyOrNever; // true +type C = IsAnyOrNever; // false +``` + +## `IsAnyOrUnknownOrNever` + +#### Signature + +```ts ignore +export type IsAnyOrUnknownOrNever = IsAny< + T, + True, + IsUnknownOrNever +>; +``` + +Resolves to [`True`](#true "Jump to symbol: 'True'") if `A` is `any`, `unknown`, +or `never`. Otherwise, it resolves to +[`False`](#false "Jump to symbol: 'False'"). + +This composite type combines [`IsAny`](#isany "Jump to symbol: 'IsAny'"), +[`IsNever`](#isnever "Jump to symbol: 'IsNever'"), and +[`IsUnknown`](#isunknown "Jump to symbol: 'IsUnknown'") into a single type-level +predicate. It's useful when creating your own custom type-level predicates, as +its usually a good idea to first check the input type is **not** `any`, +`unknown`, or `never` before moving on to the assignability of the type you're +actually interested in. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +#### Examples + +```ts +import type { IsAnyOrUnknownOrNever } from "@nick/is/type"; + +type A = IsAnyOrUnknownOrNever; // true +type B = IsAnyOrUnknownOrNever; // true +type C = IsAnyOrUnknownOrNever; // true + +type D = IsAnyOrUnknownOrNever; // false +type E = IsAnyOrUnknownOrNever<"hello">; // false +type F = IsAnyOrUnknownOrNever<1>; // false +``` + +## `IsArray` + +#### Signature + +```ts ignore +export type IsArray = IsAnyOrUnknownOrNever< + T, + False, + T extends readonly unknown[] ? True : False +>; +``` + +Resolves to [`True`](#true "Jump to symbol: 'True'") if +[`A`](#a "Jump to symbol: 'A'") is an array, which is a list of variable length +with values that can be of any type. This check **does** include tuples like +`[1, 2, 3]`, standard arrays like `string[]`, and also generic arrays like +`Array` in what it considers valid. Any other type resolves to +[`False`](#false "Jump to symbol: 'False'"). + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsArray } from "@nick/is/type"; + +type A = IsArray<[1, 2, 3]>; // true +type B = IsArray<[unknown, unkown, unknown, unknown, unknown]>; // true +type C = IsArray; // true +type D = IsArray>; // true +type E = IsArray>; // true +type F = IsArray; // true + +type G = IsArray; // false +type H = IsArray; // false +``` + +## `IsBoolean` + +#### Signature + +```ts ignore +export type IsBoolean = [T] extends [boolean] + ? [boolean] extends [T] ? True : False + : False; +``` + +Checks if the type [`T`](#t "Jump to symbol: 'T'") is the generic type +`boolean`, returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. + +This predicate is not satisfied by just `true` or `false`; the type must be a +union of both (`true | false`, which is what the `boolean` type actually +represents) to result in a positive match. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Categories + +`Types` `Boolean` + +#### Examples + +```ts +import type { IsBoolean } from "@nick/is/type/boolean"; + +type A = IsBoolean; // false +type B = IsBoolean; // false +type C = IsBoolean; // false + +type Y = IsBoolean; // true +type Z = IsBoolean; // true +``` + +## `IsExact` + +#### Signature + +```ts ignore +export type IsExact = Matches< + Eq>, + Eq>, + True, + False +>; +``` + +Type-level predicate to check if [`T`](#t "Jump to symbol: 'T'") and +[`U`](#u "Jump to symbol: 'U'") are exactly the same type in terms of their +structural assignability. If the types are an exact match, it will resolve to +[`True`](#true "Jump to symbol: 'True'") (default: true). If not, it will +resolve to [`False`](#false "Jump to symbol: 'False'") (default: false). + +You can override the `True` and `False` type parameters to customize the +behavior of this type predicate, and effectively create a type-level ternery +operation. Be mindful that while you _can_ create nested conditional type checks +with this, it is usually not recommended to do so (for the same reasons why it's +discouraged to do so with a runtime ternary operator). + +This is a strict comparison that leverages TypeScript's internal semantics +surrounding type variance and assignability, and is not just a simple +`T +extends U` check. + +##### Type Parameters + +- **`T`** +- **`U`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +#### Examples + +```ts +import type { IsExact } from "@nick/is/type/exact"; + +type A = IsExact<"hello", "hello">; // true +type B = IsExact<{ a: string | null }, { a: string | null }>; // true +type C = IsExact; // true +type D = IsExact; // true + +type E = IsExact; // false +type F = IsExact; // false +type G = IsExact<{ a: string | null }, { a: string }>; // false +type H = IsExact<{ a: string | null }, { a: string | undefined }>; // false +type I = IsExact<{ a: string; b?: number }, { a: string; b: number }>; // false +type J = IsExact<{ a: void }, { a: undefined }>; // false +type K = T.IsExact<{ a: boolean }, { a: any }>; // false +``` + +## `IsFalse` + +#### Signature + +```ts ignore +export type IsFalse = [T, false] extends + [false, T] ? True : False; +``` + +Checks if the type [`T`](#t "Jump to symbol: 'T'") is specifically `false`, +returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Categories + +`Types` `Boolean` + +#### Examples + +```ts +import type { IsFalse } from "@nick/is/type/boolean"; + +type A = IsFalse; // false +type B = IsFalse; // true +type C = IsFalse; // false +``` + +## `IsIndexSignature` + +#### Signature + +```ts ignore +export type IsIndexSignature = K extends + PropertyKey ? {} extends Record ? True : False : False; +``` + +If [`K`](#k "Jump to symbol: 'K'") is a valid index signature of an +object-literal type, this resolves to [`True`](#true "Jump to symbol: 'True'"). +Otherwise, it resolves to [`False`](#false "Jump to symbol: 'False'"). + +Index signatures are not like literal keys of an object. They do share the same +supertypes (either a string, symbol, or number), but instead of them specifying +a single property's key on the object, they define _ranges_ of keys that an +object can accept, based on their type. + +Visually, they are surrounded with square brackets, similar to computed +properties. Inside of the square brackets, the index signature's label and type +are defined. + +##### Type Parameters + +- **`K`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +#### Signature + +```ts ignore +type ArrayLike = { + readonly length: number; // <- standard property + [index: number]: T | undefined; // <- index signature +}; + +// using `IsIndexSignature` to filter out index signatures +type WithoutIndexSignature = { + [K in keyof T as IsIndexSignature]: T[K]; +}; + +type IsolateIndexSignature = { + [K in keyof T as IsIndexSignature]: T[K]; +}; + +type A = WithoutIndexSignature>; +// ^? type A = { readonly length: number } + +type B = IsolateIndexSignature>; +// ^? type B = { readonly [index: number]: string | undefined } +``` + +This type is often used for mostly cosmetic purposes, as index signatures tend +to make a type look less clean; however, it also serves a practical purpose, +allowing you to make a type more specific and restrict the keys that can be used +with it to only those that are explicitly defined. + +## `IsLiteral` + +#### Signature + +```ts ignore +export type IsLiteral = [T] extends [never] + ? False + : [T] extends [null] ? True + : [T] extends [undefined] ? True + : [T] extends [boolean] ? IsBoolean + : [T] extends [number] ? number extends T ? False : True + : [T] extends [string] ? string extends T ? False : True + : [T] extends [bigint] ? bigint extends T ? False : True + : [T] extends [symbol] ? symbol extends T ? False : True + : [T] extends [Record] + ? Record extends T ? False : True + : T extends readonly [] | readonly [any, ...readonly any[]] + ? number extends T["length"] ? False : True + : [T] extends [object] ? object extends T ? False : True + : False; +``` + +If the given type [`T`](#t "Jump to symbol: 'T'") is a literal value (meaning a +string, number, boolean, bigint, symbol, object literal, or a tuple), this type +will resolve to the [`True`](#true "Jump to symbol: 'True'") type parameter, +which has a default value of `true`. Otherwise it resolves to the +[`False`](#false "Jump to symbol: 'False'") type parameter, which has a default +value of `false`. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsLiteral } from "@nick/is/type"; + +type A1 = IsLiteral<"foo">; // true +type A2 = IsLiteral; // false +``` + +## `IsNever` + +#### Signature + +```ts ignore +export type IsNever = [T] extends [never] ? True + : False; +``` + +Check if the type [`T`](#t "Jump to symbol: 'T'") is specifically `never`, +returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsNever } from "@nick/is/type/never"; + +type A = IsNever; // true +type B = IsNever; // "never" +``` + +## `IsNonTupleArray` + +#### Signature + +```ts ignore +export type IsNonTupleArray = IsArray< + T, + IsTuple, + False +>; +``` + +Resolves to [`True`](#true "Jump to symbol: 'True'") if +[`A`](#a "Jump to symbol: 'A'") is an array, but **not** a tuple. This check +includes standard arrays like `string[]` and generic arrays like +`Array`, but **excludes** tuples like `[1, 2, 3]`. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsNonTupleArray } from "@nick/is/type"; + +type A = IsNonTupleArray<[1, 2, 3]>; // false +type B = IsNonTupleArray<[unknown, unkown, unknown]>; // false +type C = IsNonTupleArray; // true +type D = IsNonTupleArray>; // true +``` + +## `IsNull` + +#### Signature + +```ts ignore +export type IsNull = [T] extends [never] ? False + : [T] extends [null] ? True + : False; +``` + +Checks if the type [`T`](#t "Jump to symbol: 'T'") is specifically `null`, +returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsNull } from "@nick/is/type"; + +type A = IsNull; // true +type B = IsNull; // false +type C = IsNull; // false +``` + +## `IsNumeric` + +#### Signature + +```ts ignore +export type IsNumeric = T extends number | bigint + ? True + : T extends `${number}` | `${bigint}` ? True + : T extends `${number}${string}` ? True + : False; +``` + +If the given string [`T`](#t "Jump to symbol: 'T'") is numeric (meaning a +literal number like `0`, a literal bigint like `0n`, the generic types `number` +or `bigint`, or generic numeric string like `${number}` or `${bigint}`), this +type resolves to the [`True`](#true "Jump to symbol: 'True'") type parameter +(defaults: `true`). Everything else will resolve to the +[`False`](#false "Jump to symbol: 'False'") parameter (default: `false`). + +Similar to the other utility types in this module, the parameterization of this +type's conditional `true` and `false` branches allows for both simple inline +conditional type checks as well as more complex nested conditionals, without the +need for any `x extends y ? a : b` ternaries. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +// simplified tuple traversal +declare function map( + array: [...A], + fn: (input: A[number], index: number) => B, +): [...{ [K in keyof A]: IsNumeric }]; + +const result = map([1, 2, 3], (x) => x * 2); +// ^? const result: [number, number, number] +``` + +## `IsTrue` + +#### Signature + +```ts ignore +export type IsTrue = [T, true] extends [true, T] + ? True + : False; +``` + +Checks if the type [`T`](#t "Jump to symbol: 'T'") is specifically `true`, +returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Categories + +`Types` `Boolean` + +#### Examples + +```ts +import type { IsTrue } from "@nick/is/type/boolean"; + +type A = IsTrue; // true +type B = IsTrue; // false +type C = IsTrue; // false +``` + +## `IsTuple` + +#### Signature + +```ts ignore +export type IsTuple = T extends + readonly [] | readonly [unknown, ...unknown[]] ? True : False; +``` + +Resolves to [`True`](#true "Jump to symbol: 'True'") if +[`A`](#a "Jump to symbol: 'A'") is a tuple, which is an array with a +pre-determined length and type for each of its elements. This check **does not** +resolve to [`True`](#true "Jump to symbol: 'True'") for arrays such as +`string[]` or `Array` (since they are not tuples), but **does** for +`[1, 2, 3]`. Any other type of value will resolve to +[`False`](#false "Jump to symbol: 'False'"). + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsTuple } from "@nick/is/type"; + +type A = IsTuple<[1, 2, 3]>; // true +type B = IsTuple; // false +type C = IsTuple>; // false +``` + +```ts +import type { IsTuple } from "@nick/is/type"; + +// using the conditional type parameters in a custom type +type EnsureTuple = IsTuple; + +type A = EnsureTuple<[1, 2, 3]>; // [1, 2, 3] +type B = EnsureTuple; // readonly [] +type C = EnsureTuple; // never +type D = EnsureTuple>; // never +``` + +## `IsUndefined` + +#### Signature + +```ts ignore +export type IsUndefined = [T] extends [never] + ? False + : [T] extends [undefined] ? [void] extends [T] ? False : True + : False; +``` + +Checks if the type [`T`](#t "Jump to symbol: 'T'") is specifically `undefined`, +returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. This does not recognize +`void` as `undefined`. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsUndefined } from "@nick/is/type"; + +type A = IsUndefined; // true +type B = IsUndefined; // false +type C = IsUndefined; // false +type D = IsUndefined; // false +``` + +## `IsUnknown` + +#### Signature + +```ts ignore +export type IsUnknown = IsAny< + A, + False, + unknowns extends A ? True : False +>; +``` + +Checks if a given type is the `unknown` type, resolving to +[`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. The `unknown` type is the +"safer" alternative to `any` in TypeScript, introduced in the TypeScript 3.0 +release (July 2018). It is a "bottom" type, meaning it is assignable to _any_ +other type, but not vice versa. This makes it a safer choice for use in type +definitions where you want to allow for any type, but still + +##### Type Parameters + +- **`A`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsUnknown } from "@nick/is/type"; + +type A = IsUnknown; // true +type B = IsUnknown; // "not unknown" +``` + +```ts +import type { IsUnknown } from "@nick/is/type"; + +type IsNotUnknown = IsUnknown; + +type A = IsNotUnknown; // never +type B = IsNotUnknown; // any +type C = IsNotUnknown; // never +type D = IsNotUnknown; // unknown[] +type E = IsNotUnknown; // string +``` + +```ts +import type { IsUnknown } from "@nick/is/type"; + +type OmitUnknown = U extends + infer T extends object ? { + [K in keyof T as IsUnknown]: Deep extends true + ? OmitUnknown + : T[K]; + } + : IsUnknown; + +declare const userData: OmitUnknown<{ + id: string; + name: string; + age: number; + data: unknown; // <-- this will be omitted +}>; +userData; +// ^? const userData: { id: string; name: string; age: number } +``` + +## `IsUnknownOrNever` + +#### Signature + +```ts ignore +export type IsUnknownOrNever = IsNever< + A, + True, + IsUnknown +>; +``` + +Resolves to [`True`](#true "Jump to symbol: 'True'") if +[`A`](#a "Jump to symbol: 'A'") is `unknown` or is `never`, and nothing else. +Otherwise, it resolves to [`False`](#false "Jump to symbol: 'False'"). This is a +convenience type combining the +[IsUnknown](#isunknown "Jump to symbol: 'IsUnknown'") and +[IsNever](#isnever "Jump to symbol: 'IsNever'") guards into a single type. + +##### Type Parameters + +- **`A`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsUnknownOrNever } from "@nick/is/type"; + +type A = IsUnknownOrNever; // true +type B = IsUnknownOrNever; // true +type C = IsUnknownOrNever; // false +type D = IsUnknownOrNever; // false +``` + +## `OmitAny` + +#### Signature + +```ts ignore +export type OmitAny = T extends object ? { + [K in [object Object]]: Deep extends true ? OmitAny : T[K] + } : T; +``` + +Omit properties from an object type where the value is `any`. This relies on the +[`IsAny`](#isany "Jump to symbol: 'IsAny'") utility type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitAny } from "@nick/is/type"; + +type A = { a: string; b: any; c: number }; +type B = OmitAny; +// ^? type B = { a: string; c: number } +``` + +## `OmitAnyOrNever` + +#### Signature + +```ts ignore +export type OmitAnyOrNever = T extends object ? { + [K in [object Object]]: + Deep extends true ? OmitAnyOrNever : T[K] + } : T; +``` + +Omit properties from an object type where the value is `any` or `never`. This +relies on the [`IsAnyOrNever`](#isanyornever "Jump to symbol: 'IsAnyOrNever'") +utility type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitAnyOrNever } from "@nick/is/type"; + +type A = { a: string; b: any; c: number; d: never }; +type B = OmitAnyOrNever; +// ^? type B = { a: string; c: number } +``` + +## `OmitAnyUnknownNever` + +#### Signature + +```ts ignore +export type OmitAnyUnknownNever = U extends infer T extends object ? { + [K in [object Object]]: + Deep extends true ? OmitAnyUnknownNever : T[K] + } : IsAnyOrUnknownOrNever; +``` + +Omit properties from an object type where the value is `any`, `unknown`, or +`never`. This relies on the +[`IsAnyOrUnknownOrNever`](#isanyorunknownornever "Jump to symbol: 'IsAnyOrUnknownOrNever'") +utility type. + +##### Type Parameters + +- **`U`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitAnyUnknownNever } from "@nick/is/type"; + +type A = { a: string; b: any; c: number; d: unknown; e: ""; f: never }; +type B = OmitAnyUnknownNever; +// ^? type B = { a: string; c: number; e: "" } +``` + +## `OmitIndexSignature` + +#### Signature + +```ts ignore +export type OmitIndexSignature = { + [K in [object Object]]: T[K] + }; +``` + +Omit generic index signatures from an object type. This is useful for filtering +out index signatures that are too broad, allowing you to clean up a type so it +only contains literal properties. + +This relies on the +[`IsIndexSignature`](#isindexsignature "Jump to symbol: 'IsIndexSignature'") +utility type. + +##### Type Parameters + +- **`T`** + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitIndexSignature } from "@nick/is/type"; + +type A = { 0: "foo"; length: 1; [y: number]: string }; +type B = OmitIndexSignature; +// ^? type B = { 0: "foo"; length: 1 } +``` + +## `OmitNever` + +#### Signature + +```ts ignore +export type OmitNever = T extends object ? { + [K in [object Object]]: Deep extends true ? OmitNever : T[K] + } : T; +``` + +Omit properties from an object type where the value is `never`. + +This relies on the [`IsNever`](#isnever "Jump to symbol: 'IsNever'") utility +type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitNever } from "@nick/is/type/never"; + +type A = Required<{ a: string; b: number } & { b: bigint; c: number }>; +// ^? type A = { a: string; b: never; c: number } + +type B = OmitNever; +// ^? type B = { a: string; c: number } +``` + +## `OmitNull` + +#### Signature + +```ts ignore +export type OmitNull = T extends object ? { + [K in [object Object]]: Deep extends true ? OmitNull : T[K] + } : T; +``` + +Omit properties from an object type where the value is `null`. This relies on +the [`IsNever`](#isnever "Jump to symbol: 'IsNever'") utility type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitNull } from "@nick/is/type"; + +type A = { a: string; b: null; c: number }; +type B = OmitNull; +// ^? type B = { a: string; c: number } +``` + +## `OmitUndefined` + +#### Signature + +```ts ignore +export type OmitUndefined = T extends object ? { + [K in [object Object]]: Deep extends true ? OmitUndefined : T[K] + } : T; +``` + +Omit properties from an object type where the value is `undefined`. This relies +on the [`IsNever`](#isnever "Jump to symbol: 'IsNever'") utility type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitUndefined } from "@nick/is/type"; + +type A = { a: string; b: undefined; c: number }; +type B = OmitUndefined; +// ^? type B = { a: string; c: number } +``` + +## `OmitUnknown` + +#### Signature + +```ts ignore +export type OmitUnknown = U extends infer T extends object ? { + [K in [object Object]]: Deep extends true ? OmitUnknown : T[K] + } : IsUnknown; +``` + +Omit properties from an object type where the value is `unknown`. + +This relies on the [`IsUnknown`](#isunknown "Jump to symbol: 'IsUnknown'") +utility type. + +##### Type Parameters + +- **`U`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitUnknown } from "@nick/is/type"; + +type A = { a: string; b: unknown; c: number }; +type B = OmitUnknown; +// ^? type B = { a: string; c: number } +``` + +## `OmitUnknownOrNever` + +#### Signature + +```ts ignore +export type OmitUnknownOrNever = U extends infer T extends object ? { + [K in [object Object]]: + Deep extends true ? OmitUnknownOrNever : T[K] + } : IsUnknownOrNever; +``` + +Omit properties from an object type where the value is `unknown` or `never`. +This relies on the +[`IsUnknownOrNever`](#isunknownornever "Jump to symbol: 'IsUnknownOrNever'") +utility type. + +##### Type Parameters + +- **`U`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitUnknownOrNever } from "@nick/is/type"; + +type A = { a: string; b: unknown; c: number }; +type B = OmitUnknownOrNever; +// ^? type B = { a: string; c: number } +``` + +## `Predicate` + +#### Signature + +```ts ignore +export type Predicate< + Type extends Base = any, + Base = unknown, + Args extends readonly unknown[] = any[], +> = Expand<(it: Base, ...args: Args) => it is Type>; +``` + +Represents a type guard (predicate function) that checks if a given value of the +base type `Base` is also of the derived type `Type`. + +##### Type Parameters + +- **`Type`** extends `Base` (default: `any`) +- **`Base`** (default: `unknown`) +- **`Args`** extends `readonly unknown[]` (default: `any[]`) + +--- + +#### Examples + +```ts +const isString: Predicate = (it: unknown): it is string => ( + typeof it === "string" +); +``` + +## `unknown` + +#### Signature + +```ts ignore +export type unknown = + | {} + | null + | undefined; +``` + +This is an alias for the built-in `unknown` type in TypeScript. It is used by +the [`IsUnknown`](#isunknown "Jump to symbol: 'IsUnknown'") type guard, and +represents any value that is not `null` or `undefined`. + +This is provided as a public export for users who want to use it in their own +type definitions but without relying on built-in `unknown` types; it's also +provided for users who are using an older version of TypeScript that does not +support `unknown` yet. + +###### Category + +`Types` + +## `unknowns` + +#### Signature + +```ts ignore +export type unknowns = + | {} + | null + | undefined; +``` + +This is an alias for the built-in `unknown` type in TypeScript. It is used by +the [`IsUnknown`](#isunknown "Jump to symbol: 'IsUnknown'") type guard, and +represents any value that is not `null` or `undefined`. + +This is provided as a public export for users who want to use it in their own +type definitions but without relying on built-in `unknown` types; it's also +provided for users who are using an older version of TypeScript that does not +support `unknown` yet. + +###### Category + +`Types` diff --git a/docs/type/never.md b/docs/type/never.md new file mode 100644 index 0000000..13e14a4 --- /dev/null +++ b/docs/type/never.md @@ -0,0 +1,73 @@ +# @nick/is/type/never + +## `IsNever` + +#### Signature + +```ts ignore +export type IsNever = [T] extends [never] ? True + : False; +``` + +Check if the type [`T`](#t "Jump to symbol: 'T'") is specifically `never`, +returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsNever } from "@nick/is/type/never"; + +type A = IsNever; // true +type B = IsNever; // "never" +``` + +## `OmitNever` + +#### Signature + +```ts ignore +export type OmitNever = T extends object ? { + [K in [object Object]]: Deep extends true ? OmitNever : T[K] + } : T; +``` + +Omit properties from an object type where the value is `never`. + +This relies on the [`IsNever`](#isnever "Jump to symbol: 'IsNever'") utility +type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitNever } from "@nick/is/type/never"; + +type A = Required<{ a: string; b: number } & { b: bigint; c: number }>; +// ^? type A = { a: string; b: never; c: number } + +type B = OmitNever; +// ^? type B = { a: string; c: number } +``` diff --git a/docs/type/null.md b/docs/type/null.md new file mode 100644 index 0000000..71de0f1 --- /dev/null +++ b/docs/type/null.md @@ -0,0 +1,71 @@ +# @nick/is/type/null + +## `IsNull` + +#### Signature + +```ts ignore +export type IsNull = [T] extends [never] ? False + : [T] extends [null] ? True + : False; +``` + +Checks if the type [`T`](#t "Jump to symbol: 'T'") is specifically `null`, +returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsNull } from "@nick/is/type"; + +type A = IsNull; // true +type B = IsNull; // false +type C = IsNull; // false +``` + +## `OmitNull` + +#### Signature + +```ts ignore +export type OmitNull = T extends object ? { + [K in [object Object]]: Deep extends true ? OmitNull : T[K] + } : T; +``` + +Omit properties from an object type where the value is `null`. This relies on +the [`IsNever`](#isnever "Jump to symbol: 'IsNever'") utility type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitNull } from "@nick/is/type"; + +type A = { a: string; b: null; c: number }; +type B = OmitNull; +// ^? type B = { a: string; c: number } +``` diff --git a/docs/type/numeric.md b/docs/type/numeric.md new file mode 100644 index 0000000..8a69c60 --- /dev/null +++ b/docs/type/numeric.md @@ -0,0 +1,50 @@ +# @nick/is/type/numeric + +## `IsNumeric` + +#### Signature + +```ts ignore +export type IsNumeric = T extends number | bigint + ? True + : T extends `${number}` | `${bigint}` ? True + : T extends `${number}${string}` ? True + : False; +``` + +If the given string [`T`](#t "Jump to symbol: 'T'") is numeric (meaning a +literal number like `0`, a literal bigint like `0n`, the generic types `number` +or `bigint`, or generic numeric string like `${number}` or `${bigint}`), this +type resolves to the [`True`](#true "Jump to symbol: 'True'") type parameter +(defaults: `true`). Everything else will resolve to the +[`False`](#false "Jump to symbol: 'False'") parameter (default: `false`). + +Similar to the other utility types in this module, the parameterization of this +type's conditional `true` and `false` branches allows for both simple inline +conditional type checks as well as more complex nested conditionals, without the +need for any `x extends y ? a : b` ternaries. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +// simplified tuple traversal +declare function map( + array: [...A], + fn: (input: A[number], index: number) => B, +): [...{ [K in keyof A]: IsNumeric }]; + +const result = map([1, 2, 3], (x) => x * 2); +// ^? const result: [number, number, number] +``` diff --git a/docs/type/omit.md b/docs/type/omit.md new file mode 100644 index 0000000..3f614bc --- /dev/null +++ b/docs/type/omit.md @@ -0,0 +1,253 @@ +# @nick/is/type/omit + +## `OmitAny` + +#### Signature + +```ts ignore +export type OmitAny = T extends object ? { + [K in [object Object]]: Deep extends true ? OmitAny : T[K] + } : T; +``` + +Omit properties from an object type where the value is `any`. + +This relies on the [`IsAny`](#isany "Jump to symbol: 'IsAny'") utility type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitAny } from "@nick/is/type"; + +type A = { a: string; b: any; c: number }; +type B = OmitAny; +// ^? type B = { a: string; c: number } +``` + +## `OmitAnyOrNever` + +#### Signature + +```ts ignore +export type OmitAnyOrNever = T extends object ? { + [K in [object Object]]: + Deep extends true ? OmitAnyOrNever : T[K] + } : T; +``` + +Omit properties from an object type where the value is `any` or `never`. + +This relies on the +[`IsAnyOrNever`](#isanyornever "Jump to symbol: 'IsAnyOrNever'") utility type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitAnyOrNever } from "@nick/is/type"; + +type A = { a: string; b: any; c: number; d: never }; +type B = OmitAnyOrNever; +// ^? type B = { a: string; c: number } +``` + +## `OmitIndexSignature` + +#### Signature + +```ts ignore +export type OmitIndexSignature = { + [K in [object Object]]: T[K] + }; +``` + +Omit generic index signatures from an object type. This is useful for filtering +out index signatures that are too broad, allowing you to clean up a type so it +only contains literal properties. + +This relies on the +[`IsIndexSignature`](#isindexsignature "Jump to symbol: 'IsIndexSignature'") +utility type. + +##### Type Parameters + +- **`T`** + +--- + +#### Examples + +```ts +import type { OmitIndexSignature } from "@nick/is/type"; + +type A = { 0: "foo"; length: 1; [y: number]: string }; +type B = OmitIndexSignature; +// ^? type B = { 0: "foo"; length: 1 } +``` + +## `OmitNever` + +#### Signature + +```ts ignore +export type OmitNever = T extends object ? { + [K in [object Object]]: Deep extends true ? OmitNever : T[K] + } : T; +``` + +Omit properties from an object type where the value is `never`. + +This relies on the [`IsNever`](#isnever "Jump to symbol: 'IsNever'") utility +type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitNever } from "@nick/is/type"; + +type A = Required<{ a: string; b: number } & { b: bigint; c: number }>; +// ^? type A = { a: string; b: never; c: number } + +type B = OmitNever; +// ^? type B = { a: string; c: number } +``` + +## `OmitNullable` + +#### Signature + +```ts ignore +export type OmitNullable = T extends object ? { + [K in [object Object]]: Deep extends true ? OmitNullable : T[K] + } : T; +``` + +Omit properties from an object type whose value is `null` or `undefined`. + +This relies on the [`IsNever`](#isnever "Jump to symbol: 'IsNever'") utility +type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitNullable } from "@nick/is/type"; + +type A = { a: string; b: null; c: number; d: undefined }; +type B = OmitNullable; +// ^? type B = { a: string; c: number } +``` + +## `OmitUndefined` + +#### Signature + +```ts ignore +export type OmitUndefined = T extends object ? { + [K in [object Object]]: Deep extends true ? OmitUndefined : T[K] + } : T; +``` + +Omit properties from an object type whose value is `undefined`. + +This relies on the [`IsNever`](#isnever "Jump to symbol: 'IsNever'") utility +type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitUndefined } from "@nick/is/type"; + +type A = { a: string; b: undefined; c: number }; +type B = OmitUndefined; +// ^? type B = { a: string; c: number } +``` + +## `OmitUnknown` + +#### Signature + +```ts ignore +export type OmitUnknown = U extends infer T extends object ? { + [K in [object Object]]: Deep extends true ? OmitUnknown : T[K] + } : IsUnknown; +``` + +Omit properties from an object type where the value is `unknown`. + +This relies on the [`IsUnknown`](#isunknown "Jump to symbol: 'IsUnknown'") +utility type. + +##### Type Parameters + +- **`U`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitUnknown } from "@nick/is/type"; + +type A = { a: string; b: unknown; c: number }; +type B = OmitUnknown; +// ^? type B = { a: string; c: number } +``` diff --git a/docs/type/predicate.md b/docs/type/predicate.md new file mode 100644 index 0000000..d4aef45 --- /dev/null +++ b/docs/type/predicate.md @@ -0,0 +1,32 @@ +# @nick/is/type/predicate + +## `Predicate` + +#### Signature + +```ts ignore +export type Predicate< + Type extends Base = any, + Base = unknown, + Args extends readonly unknown[] = any[], +> = Expand<(it: Base, ...args: Args) => it is Type>; +``` + +Represents a type guard (predicate function) that checks if a given value of the +base type `Base` is also of the derived type `Type`. + +##### Type Parameters + +- **`Type`** extends `Base` (default: `any`) +- **`Base`** (default: `unknown`) +- **`Args`** extends `readonly unknown[]` (default: `any[]`) + +--- + +#### Examples + +```ts +const isString: Predicate = (it: unknown): it is string => ( + typeof it === "string" +); +``` diff --git a/docs/type/tuple.md b/docs/type/tuple.md new file mode 100644 index 0000000..c3a3339 --- /dev/null +++ b/docs/type/tuple.md @@ -0,0 +1,52 @@ +# @nick/is/type/tuple + +## `IsTuple` + +#### Signature + +```ts ignore +export type IsTuple = T extends + readonly [] | readonly [unknown, ...unknown[]] ? True : False; +``` + +Resolves to [`True`](#true "Jump to symbol: 'True'") if +[`A`](#a "Jump to symbol: 'A'") is a tuple, which is an array with a +pre-determined length and type for each of its elements. This check **does not** +resolve to [`True`](#true "Jump to symbol: 'True'") for arrays such as +`string[]` or `Array` (since they are not tuples), but **does** for +`[1, 2, 3]`. Any other type of value will resolve to +[`False`](#false "Jump to symbol: 'False'"). + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsTuple } from "@nick/is/type"; + +type A = IsTuple<[1, 2, 3]>; // true +type B = IsTuple; // false +type C = IsTuple>; // false +``` + +```ts +import type { IsTuple } from "@nick/is/type"; + +// using the conditional type parameters in a custom type +type EnsureTuple = IsTuple; + +type A = EnsureTuple<[1, 2, 3]>; // [1, 2, 3] +type B = EnsureTuple; // readonly [] +type C = EnsureTuple; // never +type D = EnsureTuple>; // never +``` diff --git a/docs/type/undefined.md b/docs/type/undefined.md new file mode 100644 index 0000000..c3ae9c0 --- /dev/null +++ b/docs/type/undefined.md @@ -0,0 +1,74 @@ +# @nick/is/type/undefined + +## `IsUndefined` + +#### Signature + +```ts ignore +export type IsUndefined = [T] extends [never] + ? False + : [T] extends [undefined] ? [void] extends [T] ? False : True + : False; +``` + +Checks if the type [`T`](#t "Jump to symbol: 'T'") is specifically `undefined`, +returning [`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. This does not recognize +`void` as `undefined`. + +##### Type Parameters + +- **`T`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsUndefined } from "@nick/is/type"; + +type A = IsUndefined; // true +type B = IsUndefined; // false +type C = IsUndefined; // false +type D = IsUndefined; // false +``` + +## `OmitUndefined` + +#### Signature + +```ts ignore +export type OmitUndefined = T extends object ? { + [K in [object Object]]: Deep extends true ? OmitUndefined : T[K] + } : T; +``` + +Omit properties from an object type where the value is `undefined`. This relies +on the [`IsNever`](#isnever "Jump to symbol: 'IsNever'") utility type. + +##### Type Parameters + +- **`T`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitUndefined } from "@nick/is/type"; + +type A = { a: string; b: undefined; c: number }; +type B = OmitUndefined; +// ^? type B = { a: string; c: number } +``` diff --git a/docs/type/unknown-or-never.md b/docs/type/unknown-or-never.md new file mode 100644 index 0000000..cf73c97 --- /dev/null +++ b/docs/type/unknown-or-never.md @@ -0,0 +1,80 @@ +# @nick/is/type/unknown-or-never + +## `IsUnknownOrNever` + +#### Signature + +```ts ignore +export type IsUnknownOrNever = IsNever< + A, + True, + IsUnknown +>; +``` + +Resolves to [`True`](#true "Jump to symbol: 'True'") if +[`A`](#a "Jump to symbol: 'A'") is `unknown` or is `never`, and nothing else. +Otherwise, it resolves to [`False`](#false "Jump to symbol: 'False'"). This is a +convenience type combining the +[IsUnknown](#isunknown "Jump to symbol: 'IsUnknown'") and +[IsNever](#isnever "Jump to symbol: 'IsNever'") guards into a single type. + +##### Type Parameters + +- **`A`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsUnknownOrNever } from "@nick/is/type"; + +type A = IsUnknownOrNever; // true +type B = IsUnknownOrNever; // true +type C = IsUnknownOrNever; // false +type D = IsUnknownOrNever; // false +``` + +## `OmitUnknownOrNever` + +#### Signature + +```ts ignore +export type OmitUnknownOrNever = U extends infer T extends object ? { + [K in [object Object]]: + Deep extends true ? OmitUnknownOrNever : T[K] + } : IsUnknownOrNever; +``` + +Omit properties from an object type where the value is `unknown` or `never`. +This relies on the +[`IsUnknownOrNever`](#isunknownornever "Jump to symbol: 'IsUnknownOrNever'") +utility type. + +##### Type Parameters + +- **`U`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitUnknownOrNever } from "@nick/is/type"; + +type A = { a: string; b: unknown; c: number }; +type B = OmitUnknownOrNever; +// ^? type B = { a: string; c: number } +``` diff --git a/docs/type/unknown.md b/docs/type/unknown.md new file mode 100644 index 0000000..202408e --- /dev/null +++ b/docs/type/unknown.md @@ -0,0 +1,159 @@ +# @nick/is/type/unknown + +## `IsUnknown` + +#### Signature + +```ts ignore +export type IsUnknown = IsAny< + A, + False, + unknowns extends A ? True : False +>; +``` + +Checks if a given type is the `unknown` type, resolving to +[`True`](#true "Jump to symbol: 'True'") if it is, and +[`False`](#false "Jump to symbol: 'False'") if not. The `unknown` type is the +"safer" alternative to `any` in TypeScript, introduced in the TypeScript 3.0 +release (July 2018). It is a "bottom" type, meaning it is assignable to _any_ +other type, but not vice versa. This makes it a safer choice for use in type +definitions where you want to allow for any type, but still + +##### Type Parameters + +- **`A`** +- **`True`** (default: `true`) +- **`False`** (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { IsUnknown } from "@nick/is/type"; + +type A = IsUnknown; // true +type B = IsUnknown; // "not unknown" +``` + +```ts +import type { IsUnknown } from "@nick/is/type"; + +type IsNotUnknown = IsUnknown; + +type A = IsNotUnknown; // never +type B = IsNotUnknown; // any +type C = IsNotUnknown; // never +type D = IsNotUnknown; // unknown[] +type E = IsNotUnknown; // string +``` + +```ts +import type { IsUnknown } from "@nick/is/type"; + +type OmitUnknown = U extends + infer T extends object ? { + [K in keyof T as IsUnknown]: Deep extends true + ? OmitUnknown + : T[K]; + } + : IsUnknown; + +declare const userData: OmitUnknown<{ + id: string; + name: string; + age: number; + data: unknown; // <-- this will be omitted +}>; +userData; +// ^? const userData: { id: string; name: string; age: number } +``` + +## `OmitUnknown` + +#### Signature + +```ts ignore +export type OmitUnknown = U extends infer T extends object ? { + [K in [object Object]]: Deep extends true ? OmitUnknown : T[K] + } : IsUnknown; +``` + +Omit properties from an object type where the value is `unknown`. + +This relies on the [`IsUnknown`](#isunknown "Jump to symbol: 'IsUnknown'") +utility type. + +##### Type Parameters + +- **`U`** +- **`Deep`** extends `boolean` (default: `false`) + +--- + +###### Category + +`Types` + +#### Examples + +```ts +import type { OmitUnknown } from "@nick/is/type"; + +type A = { a: string; b: unknown; c: number }; +type B = OmitUnknown; +// ^? type B = { a: string; c: number } +``` + +## `unknown` + +#### Signature + +```ts ignore +export type unknown = + | {} + | null + | undefined; +``` + +This is an alias for the built-in `unknown` type in TypeScript. It is used by +the [`IsUnknown`](#isunknown "Jump to symbol: 'IsUnknown'") type guard, and +represents any value that is not `null` or `undefined`. + +This is provided as a public export for users who want to use it in their own +type definitions but without relying on built-in `unknown` types; it's also +provided for users who are using an older version of TypeScript that does not +support `unknown` yet. + +###### Category + +`Types` + +## `unknowns` + +#### Signature + +```ts ignore +export type unknowns = + | {} + | null + | undefined; +``` + +This is an alias for the built-in `unknown` type in TypeScript. It is used by +the [`IsUnknown`](#isunknown "Jump to symbol: 'IsUnknown'") type guard, and +represents any value that is not `null` or `undefined`. + +This is provided as a public export for users who want to use it in their own +type definitions but without relying on built-in `unknown` types; it's also +provided for users who are using an older version of TypeScript that does not +support `unknown` yet. + +###### Category + +`Types` From 26815269658bc96b065bb9d721aa880484248f3f Mon Sep 17 00:00:00 2001 From: Nicholas Berlette Date: Sun, 27 Jul 2025 17:10:07 +0000 Subject: [PATCH 12/24] docs: addd package.json and deno.d.ts to docs --- docs/deno.d.ts | 20929 ++++++++++++++++++++++++++++++++++++++++++++ docs/package.json | 22 + 2 files changed, 20951 insertions(+) create mode 100644 docs/deno.d.ts create mode 100644 docs/package.json diff --git a/docs/deno.d.ts b/docs/deno.d.ts new file mode 100644 index 0000000..c27d19a --- /dev/null +++ b/docs/deno.d.ts @@ -0,0 +1,20929 @@ +// Copyright 2018-2025 the Deno authors. MIT license. + +/// +/// +/// + +/** Deno provides extra properties on `import.meta`. These are included here + * to ensure that these are still available when using the Deno namespace in + * conjunction with other type libs, like `dom`. + * + * @category Platform + */ +interface ImportMeta { + /** A string representation of the fully qualified module URL. When the + * module is loaded locally, the value will be a file URL (e.g. + * `file:///path/module.ts`). + * + * You can also parse the string as a URL to determine more information about + * how the current module was loaded. For example to determine if a module was + * local or not: + * + * ```ts + * const url = new URL(import.meta.url); + * if (url.protocol === "file:") { + * console.log("this module was loaded locally"); + * } + * ``` + */ + url: string; + + /** The absolute path of the current module. + * + * This property is only provided for local modules (ie. using `file://` URLs). + * + * Example: + * ``` + * // Unix + * console.log(import.meta.filename); // /home/alice/my_module.ts + * + * // Windows + * console.log(import.meta.filename); // C:\alice\my_module.ts + * ``` + */ + filename?: string; + + /** The absolute path of the directory containing the current module. + * + * This property is only provided for local modules (ie. using `file://` URLs). + * + * * Example: + * ``` + * // Unix + * console.log(import.meta.dirname); // /home/alice + * + * // Windows + * console.log(import.meta.dirname); // C:\alice + * ``` + */ + dirname?: string; + + /** A flag that indicates if the current module is the main module that was + * called when starting the program under Deno. + * + * ```ts + * if (import.meta.main) { + * // this was loaded as the main module, maybe do some bootstrapping + * } + * ``` + */ + main: boolean; + + /** A function that returns resolved specifier as if it would be imported + * using `import(specifier)`. + * + * ```ts + * console.log(import.meta.resolve("./foo.js")); + * // file:///dev/foo.js + * ``` + */ + resolve(specifier: string): string; +} + +/** Deno supports [User Timing Level 3](https://w3c.github.io/user-timing) + * which is not widely supported yet in other runtimes. + * + * Check out the + * [Performance API](https://developer.mozilla.org/en-US/docs/Web/API/Performance) + * documentation on MDN for further information about how to use the API. + * + * @category Performance + */ +interface Performance { + /** Stores a timestamp with the associated name (a "mark"). */ + mark(markName: string, options?: PerformanceMarkOptions): PerformanceMark; + + /** Stores the `DOMHighResTimeStamp` duration between two marks along with the + * associated name (a "measure"). */ + measure( + measureName: string, + options?: PerformanceMeasureOptions, + ): PerformanceMeasure; +} + +/** + * Options which are used in conjunction with `performance.mark`. Check out the + * MDN + * [`performance.mark()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark#markoptions) + * documentation for more details. + * + * @category Performance + */ +interface PerformanceMarkOptions { + /** Metadata to be included in the mark. */ + // deno-lint-ignore no-explicit-any + detail?: any; + + /** Timestamp to be used as the mark time. */ + startTime?: number; +} + +/** + * Options which are used in conjunction with `performance.measure`. Check out the + * MDN + * [`performance.mark()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/measure#measureoptions) + * documentation for more details. + * + * @category Performance + */ +interface PerformanceMeasureOptions { + /** Metadata to be included in the measure. */ + // deno-lint-ignore no-explicit-any + detail?: any; + + /** Timestamp to be used as the start time or string to be used as start + * mark. */ + start?: string | number; + + /** Duration between the start and end times. */ + duration?: number; + + /** Timestamp to be used as the end time or string to be used as end mark. */ + end?: string | number; +} + +/** The global namespace where Deno specific, non-standard APIs are located. */ +declare namespace Deno { + /** A set of error constructors that are raised by Deno APIs. + * + * Can be used to provide more specific handling of failures within code + * which is using Deno APIs. For example, handling attempting to open a file + * which does not exist: + * + * ```ts + * try { + * const file = await Deno.open("./some/file.txt"); + * } catch (error) { + * if (error instanceof Deno.errors.NotFound) { + * console.error("the file was not found"); + * } else { + * // otherwise re-throw + * throw error; + * } + * } + * ``` + * + * @category Errors + */ + export namespace errors { + /** + * Raised when the underlying operating system indicates that the file + * was not found. + * + * @category Errors */ + export class NotFound extends Error {} + /** + * Raised when the underlying operating system indicates the current user + * which the Deno process is running under does not have the appropriate + * permissions to a file or resource. + * + * Before Deno 2.0, this error was raised when the user _did not_ provide + * required `--allow-*` flag. As of Deno 2.0, that case is now handled by + * the {@link NotCapable} error. + * + * @category Errors */ + export class PermissionDenied extends Error {} + /** + * Raised when the underlying operating system reports that a connection to + * a resource is refused. + * + * @category Errors */ + export class ConnectionRefused extends Error {} + /** + * Raised when the underlying operating system reports that a connection has + * been reset. With network servers, it can be a _normal_ occurrence where a + * client will abort a connection instead of properly shutting it down. + * + * @category Errors */ + export class ConnectionReset extends Error {} + /** + * Raised when the underlying operating system reports an `ECONNABORTED` + * error. + * + * @category Errors */ + export class ConnectionAborted extends Error {} + /** + * Raised when the underlying operating system reports an `ENOTCONN` error. + * + * @category Errors */ + export class NotConnected extends Error {} + /** + * Raised when attempting to open a server listener on an address and port + * that already has a listener. + * + * @category Errors */ + export class AddrInUse extends Error {} + /** + * Raised when the underlying operating system reports an `EADDRNOTAVAIL` + * error. + * + * @category Errors */ + export class AddrNotAvailable extends Error {} + /** + * Raised when trying to write to a resource and a broken pipe error occurs. + * This can happen when trying to write directly to `stdout` or `stderr` + * and the operating system is unable to pipe the output for a reason + * external to the Deno runtime. + * + * @category Errors */ + export class BrokenPipe extends Error {} + /** + * Raised when trying to create a resource, like a file, that already + * exits. + * + * @category Errors */ + export class AlreadyExists extends Error {} + /** + * Raised when an operation to returns data that is invalid for the + * operation being performed. + * + * @category Errors */ + export class InvalidData extends Error {} + /** + * Raised when the underlying operating system reports that an I/O operation + * has timed out (`ETIMEDOUT`). + * + * @category Errors */ + export class TimedOut extends Error {} + /** + * Raised when the underlying operating system reports an `EINTR` error. In + * many cases, this underlying IO error will be handled internally within + * Deno, or result in an @{link BadResource} error instead. + * + * @category Errors */ + export class Interrupted extends Error {} + /** + * Raised when the underlying operating system would need to block to + * complete but an asynchronous (non-blocking) API is used. + * + * @category Errors */ + export class WouldBlock extends Error {} + /** + * Raised when expecting to write to a IO buffer resulted in zero bytes + * being written. + * + * @category Errors */ + export class WriteZero extends Error {} + /** + * Raised when attempting to read bytes from a resource, but the EOF was + * unexpectedly encountered. + * + * @category Errors */ + export class UnexpectedEof extends Error {} + /** + * The underlying IO resource is invalid or closed, and so the operation + * could not be performed. + * + * @category Errors */ + export class BadResource extends Error {} + /** + * Raised in situations where when attempting to load a dynamic import, + * too many redirects were encountered. + * + * @category Errors */ + export class Http extends Error {} + /** + * Raised when the underlying IO resource is not available because it is + * being awaited on in another block of code. + * + * @category Errors */ + export class Busy extends Error {} + /** + * Raised when the underlying Deno API is asked to perform a function that + * is not currently supported. + * + * @category Errors */ + export class NotSupported extends Error {} + /** + * Raised when too many symbolic links were encountered when resolving the + * filename. + * + * @category Errors */ + export class FilesystemLoop extends Error {} + /** + * Raised when trying to open, create or write to a directory. + * + * @category Errors */ + export class IsADirectory extends Error {} + /** + * Raised when performing a socket operation but the remote host is + * not reachable. + * + * @category Errors */ + export class NetworkUnreachable extends Error {} + /** + * Raised when trying to perform an operation on a path that is not a + * directory, when directory is required. + * + * @category Errors */ + export class NotADirectory extends Error {} + + /** + * Raised when trying to perform an operation while the relevant Deno + * permission (like `--allow-read`) has not been granted. + * + * Before Deno 2.0, this condition was covered by the {@link PermissionDenied} + * error. + * + * @category Errors */ + export class NotCapable extends Error {} + + export {}; // only export exports + } + + /** The current process ID of this instance of the Deno CLI. + * + * ```ts + * console.log(Deno.pid); + * ``` + * + * @category Runtime + */ + export const pid: number; + + /** + * The process ID of parent process of this instance of the Deno CLI. + * + * ```ts + * console.log(Deno.ppid); + * ``` + * + * @category Runtime + */ + export const ppid: number; + + /** @category Runtime */ + export interface MemoryUsage { + /** The number of bytes of the current Deno's process resident set size, + * which is the amount of memory occupied in main memory (RAM). */ + rss: number; + /** The total size of the heap for V8, in bytes. */ + heapTotal: number; + /** The amount of the heap used for V8, in bytes. */ + heapUsed: number; + /** Memory, in bytes, associated with JavaScript objects outside of the + * JavaScript isolate. */ + external: number; + } + + /** + * Returns an object describing the memory usage of the Deno process and the + * V8 subsystem measured in bytes. + * + * @category Runtime + */ + export function memoryUsage(): MemoryUsage; + + /** + * Get the `hostname` of the machine the Deno process is running on. + * + * ```ts + * console.log(Deno.hostname()); + * ``` + * + * Requires `allow-sys` permission. + * + * @tags allow-sys + * @category Runtime + */ + export function hostname(): string; + + /** + * Returns an array containing the 1, 5, and 15 minute load averages. The + * load average is a measure of CPU and IO utilization of the last one, five, + * and 15 minute periods expressed as a fractional number. Zero means there + * is no load. On Windows, the three values are always the same and represent + * the current load, not the 1, 5 and 15 minute load averages. + * + * ```ts + * console.log(Deno.loadavg()); // e.g. [ 0.71, 0.44, 0.44 ] + * ``` + * + * Requires `allow-sys` permission. + * + * On Windows there is no API available to retrieve this information and this method returns `[ 0, 0, 0 ]`. + * + * @tags allow-sys + * @category Runtime + */ + export function loadavg(): number[]; + + /** + * The information for a network interface returned from a call to + * {@linkcode Deno.networkInterfaces}. + * + * @category Network + */ + export interface NetworkInterfaceInfo { + /** The network interface name. */ + name: string; + /** The IP protocol version. */ + family: "IPv4" | "IPv6"; + /** The IP address bound to the interface. */ + address: string; + /** The netmask applied to the interface. */ + netmask: string; + /** The IPv6 scope id or `null`. */ + scopeid: number | null; + /** The CIDR range. */ + cidr: string; + /** The MAC address. */ + mac: string; + } + + /** + * Returns an array of the network interface information. + * + * ```ts + * console.log(Deno.networkInterfaces()); + * ``` + * + * Requires `allow-sys` permission. + * + * @tags allow-sys + * @category Network + */ + export function networkInterfaces(): NetworkInterfaceInfo[]; + + /** + * Displays the total amount of free and used physical and swap memory in the + * system, as well as the buffers and caches used by the kernel. + * + * This is similar to the `free` command in Linux + * + * ```ts + * console.log(Deno.systemMemoryInfo()); + * ``` + * + * Requires `allow-sys` permission. + * + * @tags allow-sys + * @category Runtime + */ + export function systemMemoryInfo(): SystemMemoryInfo; + + /** + * Information returned from a call to {@linkcode Deno.systemMemoryInfo}. + * + * @category Runtime + */ + export interface SystemMemoryInfo { + /** Total installed memory in bytes. */ + total: number; + /** Unused memory in bytes. */ + free: number; + /** Estimation of how much memory, in bytes, is available for starting new + * applications, without swapping. Unlike the data provided by the cache or + * free fields, this field takes into account page cache and also that not + * all reclaimable memory will be reclaimed due to items being in use. + */ + available: number; + /** Memory used by kernel buffers. */ + buffers: number; + /** Memory used by the page cache and slabs. */ + cached: number; + /** Total swap memory. */ + swapTotal: number; + /** Unused swap memory. */ + swapFree: number; + } + + /** Reflects the `NO_COLOR` environment variable at program start. + * + * When the value is `true`, the Deno CLI will attempt to not send color codes + * to `stderr` or `stdout` and other command line programs should also attempt + * to respect this value. + * + * See: https://no-color.org/ + * + * @category Runtime + */ + export const noColor: boolean; + + /** + * Returns the release version of the Operating System. + * + * ```ts + * console.log(Deno.osRelease()); + * ``` + * + * Requires `allow-sys` permission. + * Under consideration to possibly move to Deno.build or Deno.versions and if + * it should depend sys-info, which may not be desirable. + * + * @tags allow-sys + * @category Runtime + */ + export function osRelease(): string; + + /** + * Returns the Operating System uptime in number of seconds. + * + * ```ts + * console.log(Deno.osUptime()); + * ``` + * + * Requires `allow-sys` permission. + * + * @tags allow-sys + * @category Runtime + */ + export function osUptime(): number; + + /** + * Options which define the permissions within a test or worker context. + * + * `"inherit"` ensures that all permissions of the parent process will be + * applied to the test context. `"none"` ensures the test context has no + * permissions. A `PermissionOptionsObject` provides a more specific + * set of permissions to the test context. + * + * @category Permissions */ + export type PermissionOptions = "inherit" | "none" | PermissionOptionsObject; + + /** + * A set of options which can define the permissions within a test or worker + * context at a highly specific level. + * + * @category Permissions */ + export interface PermissionOptionsObject { + /** Specifies if the `env` permission should be requested or revoked. + * If set to `"inherit"`, the current `env` permission will be inherited. + * If set to `true`, the global `env` permission will be requested. + * If set to `false`, the global `env` permission will be revoked. + * + * @default {false} + */ + env?: "inherit" | boolean | string[]; + + /** Specifies if the `ffi` permission should be requested or revoked. + * If set to `"inherit"`, the current `ffi` permission will be inherited. + * If set to `true`, the global `ffi` permission will be requested. + * If set to `false`, the global `ffi` permission will be revoked. + * + * @default {false} + */ + ffi?: "inherit" | boolean | Array; + + /** Specifies if the `import` permission should be requested or revoked. + * If set to `"inherit"` the current `import` permission will be inherited. + * If set to `true`, the global `import` permission will be requested. + * If set to `false`, the global `import` permission will be revoked. + * If set to `Array`, the `import` permissions will be requested with the + * specified domains. + */ + import?: "inherit" | boolean | Array; + + /** Specifies if the `net` permission should be requested or revoked. + * if set to `"inherit"`, the current `net` permission will be inherited. + * if set to `true`, the global `net` permission will be requested. + * if set to `false`, the global `net` permission will be revoked. + * if set to `string[]`, the `net` permission will be requested with the + * specified host strings with the format `"[:]`. + * + * @default {false} + * + * Examples: + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.test({ + * name: "inherit", + * permissions: { + * net: "inherit", + * }, + * async fn() { + * const status = await Deno.permissions.query({ name: "net" }) + * assertEquals(status.state, "granted"); + * }, + * }); + * ``` + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.test({ + * name: "true", + * permissions: { + * net: true, + * }, + * async fn() { + * const status = await Deno.permissions.query({ name: "net" }); + * assertEquals(status.state, "granted"); + * }, + * }); + * ``` + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.test({ + * name: "false", + * permissions: { + * net: false, + * }, + * async fn() { + * const status = await Deno.permissions.query({ name: "net" }); + * assertEquals(status.state, "denied"); + * }, + * }); + * ``` + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.test({ + * name: "localhost:8080", + * permissions: { + * net: ["localhost:8080"], + * }, + * async fn() { + * const status = await Deno.permissions.query({ name: "net", host: "localhost:8080" }); + * assertEquals(status.state, "granted"); + * }, + * }); + * ``` + */ + net?: "inherit" | boolean | string[]; + + /** Specifies if the `read` permission should be requested or revoked. + * If set to `"inherit"`, the current `read` permission will be inherited. + * If set to `true`, the global `read` permission will be requested. + * If set to `false`, the global `read` permission will be revoked. + * If set to `Array`, the `read` permission will be requested with the + * specified file paths. + * + * @default {false} + */ + read?: "inherit" | boolean | Array; + + /** Specifies if the `run` permission should be requested or revoked. + * If set to `"inherit"`, the current `run` permission will be inherited. + * If set to `true`, the global `run` permission will be requested. + * If set to `false`, the global `run` permission will be revoked. + * + * @default {false} + */ + run?: "inherit" | boolean | Array; + + /** Specifies if the `sys` permission should be requested or revoked. + * If set to `"inherit"`, the current `sys` permission will be inherited. + * If set to `true`, the global `sys` permission will be requested. + * If set to `false`, the global `sys` permission will be revoked. + * + * @default {false} + */ + sys?: "inherit" | boolean | string[]; + + /** Specifies if the `write` permission should be requested or revoked. + * If set to `"inherit"`, the current `write` permission will be inherited. + * If set to `true`, the global `write` permission will be requested. + * If set to `false`, the global `write` permission will be revoked. + * If set to `Array`, the `write` permission will be requested with the + * specified file paths. + * + * @default {false} + */ + write?: "inherit" | boolean | Array; + } + + /** + * Context that is passed to a testing function, which can be used to either + * gain information about the current test, or register additional test + * steps within the current test. + * + * @category Testing */ + export interface TestContext { + /** The current test name. */ + name: string; + /** The string URL of the current test. */ + origin: string; + /** If the current test is a step of another test, the parent test context + * will be set here. */ + parent?: TestContext; + + /** Run a sub step of the parent test or step. Returns a promise + * that resolves to a boolean signifying if the step completed successfully. + * + * The returned promise never rejects unless the arguments are invalid. + * + * If the test was ignored the promise returns `false`. + * + * ```ts + * Deno.test({ + * name: "a parent test", + * async fn(t) { + * console.log("before the step"); + * await t.step({ + * name: "step 1", + * fn(t) { + * console.log("current step:", t.name); + * } + * }); + * console.log("after the step"); + * } + * }); + * ``` + */ + step(definition: TestStepDefinition): Promise; + + /** Run a sub step of the parent test or step. Returns a promise + * that resolves to a boolean signifying if the step completed successfully. + * + * The returned promise never rejects unless the arguments are invalid. + * + * If the test was ignored the promise returns `false`. + * + * ```ts + * Deno.test( + * "a parent test", + * async (t) => { + * console.log("before the step"); + * await t.step( + * "step 1", + * (t) => { + * console.log("current step:", t.name); + * } + * ); + * console.log("after the step"); + * } + * ); + * ``` + */ + step( + name: string, + fn: (t: TestContext) => void | Promise, + ): Promise; + + /** Run a sub step of the parent test or step. Returns a promise + * that resolves to a boolean signifying if the step completed successfully. + * + * The returned promise never rejects unless the arguments are invalid. + * + * If the test was ignored the promise returns `false`. + * + * ```ts + * Deno.test(async function aParentTest(t) { + * console.log("before the step"); + * await t.step(function step1(t) { + * console.log("current step:", t.name); + * }); + * console.log("after the step"); + * }); + * ``` + */ + step(fn: (t: TestContext) => void | Promise): Promise; + } + + /** @category Testing */ + export interface TestStepDefinition { + /** The test function that will be tested when this step is executed. The + * function can take an argument which will provide information about the + * current step's context. */ + fn: (t: TestContext) => void | Promise; + /** The name of the step. */ + name: string; + /** If truthy the current test step will be ignored. + * + * This is a quick way to skip over a step, but also can be used for + * conditional logic, like determining if an environment feature is present. + */ + ignore?: boolean; + /** Check that the number of async completed operations after the test step + * is the same as number of dispatched operations. This ensures that the + * code tested does not start async operations which it then does + * not await. This helps in preventing logic errors and memory leaks + * in the application code. + * + * Defaults to the parent test or step's value. */ + sanitizeOps?: boolean; + /** Ensure the test step does not "leak" resources - like open files or + * network connections - by ensuring the open resources at the start of the + * step match the open resources at the end of the step. + * + * Defaults to the parent test or step's value. */ + sanitizeResources?: boolean; + /** Ensure the test step does not prematurely cause the process to exit, + * for example via a call to {@linkcode Deno.exit}. + * + * Defaults to the parent test or step's value. */ + sanitizeExit?: boolean; + } + + /** @category Testing */ + export interface TestDefinition { + fn: (t: TestContext) => void | Promise; + /** The name of the test. */ + name: string; + /** If truthy the current test step will be ignored. + * + * It is a quick way to skip over a step, but also can be used for + * conditional logic, like determining if an environment feature is present. + */ + ignore?: boolean; + /** If at least one test has `only` set to `true`, only run tests that have + * `only` set to `true` and fail the test suite. */ + only?: boolean; + /** Check that the number of async completed operations after the test step + * is the same as number of dispatched operations. This ensures that the + * code tested does not start async operations which it then does + * not await. This helps in preventing logic errors and memory leaks + * in the application code. + * + * @default {true} */ + sanitizeOps?: boolean; + /** Ensure the test step does not "leak" resources - like open files or + * network connections - by ensuring the open resources at the start of the + * test match the open resources at the end of the test. + * + * @default {true} */ + sanitizeResources?: boolean; + /** Ensure the test case does not prematurely cause the process to exit, + * for example via a call to {@linkcode Deno.exit}. + * + * @default {true} */ + sanitizeExit?: boolean; + /** Specifies the permissions that should be used to run the test. + * + * Set this to "inherit" to keep the calling runtime permissions, set this + * to "none" to revoke all permissions, or set a more specific set of + * permissions using a {@linkcode PermissionOptionsObject}. + * + * @default {"inherit"} */ + permissions?: PermissionOptions; + } + + /** Register a test which will be run when `deno test` is used on the command + * line and the containing module looks like a test module. + * + * `fn` can be async if required. + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.test({ + * name: "example test", + * fn() { + * assertEquals("world", "world"); + * }, + * }); + * + * Deno.test({ + * name: "example ignored test", + * ignore: Deno.build.os === "windows", + * fn() { + * // This test is ignored only on Windows machines + * }, + * }); + * + * Deno.test({ + * name: "example async test", + * async fn() { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world"); + * } + * }); + * ``` + * + * @category Testing + */ + export const test: DenoTest; + + /** + * @category Testing + */ + export interface DenoTest { + /** Register a test which will be run when `deno test` is used on the command + * line and the containing module looks like a test module. + * + * `fn` can be async if required. + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.test({ + * name: "example test", + * fn() { + * assertEquals("world", "world"); + * }, + * }); + * + * Deno.test({ + * name: "example ignored test", + * ignore: Deno.build.os === "windows", + * fn() { + * // This test is ignored only on Windows machines + * }, + * }); + * + * Deno.test({ + * name: "example async test", + * async fn() { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world"); + * } + * }); + * ``` + * + * @category Testing + */ + (t: TestDefinition): void; + + /** Register a test which will be run when `deno test` is used on the command + * line and the containing module looks like a test module. + * + * `fn` can be async if required. + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.test("My test description", () => { + * assertEquals("hello", "hello"); + * }); + * + * Deno.test("My async test description", async () => { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world"); + * }); + * ``` + * + * @category Testing + */ + (name: string, fn: (t: TestContext) => void | Promise): void; + + /** Register a test which will be run when `deno test` is used on the command + * line and the containing module looks like a test module. + * + * `fn` can be async if required. Declared function must have a name. + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.test(function myTestName() { + * assertEquals("hello", "hello"); + * }); + * + * Deno.test(async function myOtherTestName() { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world"); + * }); + * ``` + * + * @category Testing + */ + (fn: (t: TestContext) => void | Promise): void; + + /** Register a test which will be run when `deno test` is used on the command + * line and the containing module looks like a test module. + * + * `fn` can be async if required. + * + * ```ts + * import { assert, fail, assertEquals } from "jsr:@std/assert"; + * + * Deno.test("My test description", { permissions: { read: true } }, (): void => { + * assertEquals("hello", "hello"); + * }); + * + * Deno.test("My async test description", { permissions: { read: false } }, async (): Promise => { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world"); + * }); + * ``` + * + * @category Testing + */ + ( + name: string, + options: Omit, + fn: (t: TestContext) => void | Promise, + ): void; + + /** Register a test which will be run when `deno test` is used on the command + * line and the containing module looks like a test module. + * + * `fn` can be async if required. + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.test( + * { + * name: "My test description", + * permissions: { read: true }, + * }, + * () => { + * assertEquals("hello", "hello"); + * }, + * ); + * + * Deno.test( + * { + * name: "My async test description", + * permissions: { read: false }, + * }, + * async () => { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world"); + * }, + * ); + * ``` + * + * @category Testing + */ + ( + options: Omit, + fn: (t: TestContext) => void | Promise, + ): void; + + /** Register a test which will be run when `deno test` is used on the command + * line and the containing module looks like a test module. + * + * `fn` can be async if required. Declared function must have a name. + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.test( + * { permissions: { read: true } }, + * function myTestName() { + * assertEquals("hello", "hello"); + * }, + * ); + * + * Deno.test( + * { permissions: { read: false } }, + * async function myOtherTestName() { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world"); + * }, + * ); + * ``` + * + * @category Testing + */ + ( + options: Omit, + fn: (t: TestContext) => void | Promise, + ): void; + + /** Shorthand property for ignoring a particular test case. + * + * @category Testing + */ + ignore(t: Omit): void; + + /** Shorthand property for ignoring a particular test case. + * + * @category Testing + */ + ignore(name: string, fn: (t: TestContext) => void | Promise): void; + + /** Shorthand property for ignoring a particular test case. + * + * @category Testing + */ + ignore(fn: (t: TestContext) => void | Promise): void; + + /** Shorthand property for ignoring a particular test case. + * + * @category Testing + */ + ignore( + name: string, + options: Omit, + fn: (t: TestContext) => void | Promise, + ): void; + + /** Shorthand property for ignoring a particular test case. + * + * @category Testing + */ + ignore( + options: Omit, + fn: (t: TestContext) => void | Promise, + ): void; + + /** Shorthand property for ignoring a particular test case. + * + * @category Testing + */ + ignore( + options: Omit, + fn: (t: TestContext) => void | Promise, + ): void; + + /** Shorthand property for focusing a particular test case. + * + * @category Testing + */ + only(t: Omit): void; + + /** Shorthand property for focusing a particular test case. + * + * @category Testing + */ + only(name: string, fn: (t: TestContext) => void | Promise): void; + + /** Shorthand property for focusing a particular test case. + * + * @category Testing + */ + only(fn: (t: TestContext) => void | Promise): void; + + /** Shorthand property for focusing a particular test case. + * + * @category Testing + */ + only( + name: string, + options: Omit, + fn: (t: TestContext) => void | Promise, + ): void; + + /** Shorthand property for focusing a particular test case. + * + * @category Testing + */ + only( + options: Omit, + fn: (t: TestContext) => void | Promise, + ): void; + + /** Shorthand property for focusing a particular test case. + * + * @category Testing + */ + only( + options: Omit, + fn: (t: TestContext) => void | Promise, + ): void; + } + + /** + * Context that is passed to a benchmarked function. The instance is shared + * between iterations of the benchmark. Its methods can be used for example + * to override of the measured portion of the function. + * + * @category Testing + */ + export interface BenchContext { + /** The current benchmark name. */ + name: string; + /** The string URL of the current benchmark. */ + origin: string; + + /** Restarts the timer for the bench measurement. This should be called + * after doing setup work which should not be measured. + * + * Warning: This method should not be used for benchmarks averaging less + * than 10μs per iteration. In such cases it will be disabled but the call + * will still have noticeable overhead, resulting in a warning. + * + * ```ts + * Deno.bench("foo", async (t) => { + * const data = await Deno.readFile("data.txt"); + * t.start(); + * // some operation on `data`... + * }); + * ``` + */ + start(): void; + + /** End the timer early for the bench measurement. This should be called + * before doing teardown work which should not be measured. + * + * Warning: This method should not be used for benchmarks averaging less + * than 10μs per iteration. In such cases it will be disabled but the call + * will still have noticeable overhead, resulting in a warning. + * + * ```ts + * Deno.bench("foo", async (t) => { + * using file = await Deno.open("data.txt"); + * t.start(); + * // some operation on `file`... + * t.end(); + * }); + * ``` + */ + end(): void; + } + + /** + * The interface for defining a benchmark test using {@linkcode Deno.bench}. + * + * @category Testing + */ + export interface BenchDefinition { + /** The test function which will be benchmarked. */ + fn: (b: BenchContext) => void | Promise; + /** The name of the test, which will be used in displaying the results. */ + name: string; + /** If truthy, the benchmark test will be ignored/skipped. */ + ignore?: boolean; + /** Group name for the benchmark. + * + * Grouped benchmarks produce a group time summary, where the difference + * in performance between each test of the group is compared. */ + group?: string; + /** Benchmark should be used as the baseline for other benchmarks. + * + * If there are multiple baselines in a group, the first one is used as the + * baseline. */ + baseline?: boolean; + /** If at least one bench has `only` set to true, only run benches that have + * `only` set to `true` and fail the bench suite. */ + only?: boolean; + /** Number of iterations to perform. + * @remarks When the benchmark is very fast, this will only be used as a + * suggestion in order to get a more accurate measurement. + */ + n?: number; + /** Number of warmups to do before running the benchmark. + * @remarks A warmup will always be performed even if this is `0` in order to + * determine the speed of the benchmark in order to improve the measurement. When + * the benchmark is very fast, this will be used as a suggestion. + */ + warmup?: number; + /** Ensure the bench case does not prematurely cause the process to exit, + * for example via a call to {@linkcode Deno.exit}. + * + * @default {true} */ + sanitizeExit?: boolean; + /** Specifies the permissions that should be used to run the bench. + * + * Set this to `"inherit"` to keep the calling thread's permissions. + * + * Set this to `"none"` to revoke all permissions. + * + * @default {"inherit"} + */ + permissions?: PermissionOptions; + } + + /** + * Register a benchmark test which will be run when `deno bench` is used on + * the command line and the containing module looks like a bench module. + * + * If the test function (`fn`) returns a promise or is async, the test runner + * will await resolution to consider the test complete. + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.bench({ + * name: "example test", + * fn() { + * assertEquals("world", "world"); + * }, + * }); + * + * Deno.bench({ + * name: "example ignored test", + * ignore: Deno.build.os === "windows", + * fn() { + * // This test is ignored only on Windows machines + * }, + * }); + * + * Deno.bench({ + * name: "example async test", + * async fn() { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world"); + * } + * }); + * ``` + * + * @category Testing + */ + export function bench(b: BenchDefinition): void; + + /** + * Register a benchmark test which will be run when `deno bench` is used on + * the command line and the containing module looks like a bench module. + * + * If the test function (`fn`) returns a promise or is async, the test runner + * will await resolution to consider the test complete. + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.bench("My test description", () => { + * assertEquals("hello", "hello"); + * }); + * + * Deno.bench("My async test description", async () => { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world"); + * }); + * ``` + * + * @category Testing + */ + export function bench( + name: string, + fn: (b: BenchContext) => void | Promise, + ): void; + + /** + * Register a benchmark test which will be run when `deno bench` is used on + * the command line and the containing module looks like a bench module. + * + * If the test function (`fn`) returns a promise or is async, the test runner + * will await resolution to consider the test complete. + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.bench(function myTestName() { + * assertEquals("hello", "hello"); + * }); + * + * Deno.bench(async function myOtherTestName() { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world"); + * }); + * ``` + * + * @category Testing + */ + export function bench(fn: (b: BenchContext) => void | Promise): void; + + /** + * Register a benchmark test which will be run when `deno bench` is used on + * the command line and the containing module looks like a bench module. + * + * If the test function (`fn`) returns a promise or is async, the test runner + * will await resolution to consider the test complete. + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.bench( + * "My test description", + * { permissions: { read: true } }, + * () => { + * assertEquals("hello", "hello"); + * } + * ); + * + * Deno.bench( + * "My async test description", + * { permissions: { read: false } }, + * async () => { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world"); + * } + * ); + * ``` + * + * @category Testing + */ + export function bench( + name: string, + options: Omit, + fn: (b: BenchContext) => void | Promise, + ): void; + + /** + * Register a benchmark test which will be run when `deno bench` is used on + * the command line and the containing module looks like a bench module. + * + * If the test function (`fn`) returns a promise or is async, the test runner + * will await resolution to consider the test complete. + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.bench( + * { name: "My test description", permissions: { read: true } }, + * () => { + * assertEquals("hello", "hello"); + * } + * ); + * + * Deno.bench( + * { name: "My async test description", permissions: { read: false } }, + * async () => { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world"); + * } + * ); + * ``` + * + * @category Testing + */ + export function bench( + options: Omit, + fn: (b: BenchContext) => void | Promise, + ): void; + + /** + * Register a benchmark test which will be run when `deno bench` is used on + * the command line and the containing module looks like a bench module. + * + * If the test function (`fn`) returns a promise or is async, the test runner + * will await resolution to consider the test complete. + * + * ```ts + * import { assertEquals } from "jsr:@std/assert"; + * + * Deno.bench( + * { permissions: { read: true } }, + * function myTestName() { + * assertEquals("hello", "hello"); + * } + * ); + * + * Deno.bench( + * { permissions: { read: false } }, + * async function myOtherTestName() { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world"); + * } + * ); + * ``` + * + * @category Testing + */ + export function bench( + options: Omit, + fn: (b: BenchContext) => void | Promise, + ): void; + + /** Exit the Deno process with optional exit code. + * + * If no exit code is supplied then Deno will exit with return code of `0`. + * + * In worker contexts this is an alias to `self.close();`. + * + * ```ts + * Deno.exit(5); + * ``` + * + * @category Runtime + */ + export function exit(code?: number): never; + + /** The exit code for the Deno process. + * + * If no exit code has been supplied, then Deno will assume a return code of `0`. + * + * When setting an exit code value, a number or non-NaN string must be provided, + * otherwise a TypeError will be thrown. + * + * ```ts + * console.log(Deno.exitCode); //-> 0 + * Deno.exitCode = 1; + * console.log(Deno.exitCode); //-> 1 + * ``` + * + * @category Runtime + */ + export var exitCode: number; + + /** An interface containing methods to interact with the process environment + * variables. + * + * @tags allow-env + * @category Runtime + */ + export interface Env { + /** Retrieve the value of an environment variable. + * + * Returns `undefined` if the supplied environment variable is not defined. + * + * ```ts + * console.log(Deno.env.get("HOME")); // e.g. outputs "/home/alice" + * console.log(Deno.env.get("MADE_UP_VAR")); // outputs "undefined" + * ``` + * + * Requires `allow-env` permission. + * + * @tags allow-env + */ + get(key: string): string | undefined; + + /** Set the value of an environment variable. + * + * ```ts + * Deno.env.set("SOME_VAR", "Value"); + * Deno.env.get("SOME_VAR"); // outputs "Value" + * ``` + * + * Requires `allow-env` permission. + * + * @tags allow-env + */ + set(key: string, value: string): void; + + /** Delete the value of an environment variable. + * + * ```ts + * Deno.env.set("SOME_VAR", "Value"); + * Deno.env.delete("SOME_VAR"); // outputs "undefined" + * ``` + * + * Requires `allow-env` permission. + * + * @tags allow-env + */ + delete(key: string): void; + + /** Check whether an environment variable is present or not. + * + * ```ts + * Deno.env.set("SOME_VAR", "Value"); + * Deno.env.has("SOME_VAR"); // outputs true + * ``` + * + * Requires `allow-env` permission. + * + * @tags allow-env + */ + has(key: string): boolean; + + /** Returns a snapshot of the environment variables at invocation as a + * simple object of keys and values. + * + * ```ts + * Deno.env.set("TEST_VAR", "A"); + * const myEnv = Deno.env.toObject(); + * console.log(myEnv.SHELL); + * Deno.env.set("TEST_VAR", "B"); + * console.log(myEnv.TEST_VAR); // outputs "A" + * ``` + * + * Requires `allow-env` permission. + * + * @tags allow-env + */ + toObject(): { [index: string]: string }; + } + + /** An interface containing methods to interact with the process environment + * variables. + * + * @tags allow-env + * @category Runtime + */ + export const env: Env; + + /** + * Returns the path to the current deno executable. + * + * ```ts + * console.log(Deno.execPath()); // e.g. "/home/alice/.local/bin/deno" + * ``` + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category Runtime + */ + export function execPath(): string; + + /** + * Change the current working directory to the specified path. + * + * ```ts + * Deno.chdir("/home/userA"); + * Deno.chdir("../userB"); + * Deno.chdir("C:\\Program Files (x86)\\Java"); + * ``` + * + * Throws {@linkcode Deno.errors.NotFound} if directory not found. + * + * Throws {@linkcode Deno.errors.PermissionDenied} if the user does not have + * operating system file access rights. + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category Runtime + */ + export function chdir(directory: string | URL): void; + + /** + * Return a string representing the current working directory. + * + * If the current directory can be reached via multiple paths (due to symbolic + * links), `cwd()` may return any one of them. + * + * ```ts + * const currentWorkingDirectory = Deno.cwd(); + * ``` + * + * Throws {@linkcode Deno.errors.NotFound} if directory not available. + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category Runtime + */ + export function cwd(): string; + + /** + * Creates `newpath` as a hard link to `oldpath`. + * + * ```ts + * await Deno.link("old/name", "new/name"); + * ``` + * + * Requires `allow-read` and `allow-write` permissions. + * + * @tags allow-read, allow-write + * @category File System + */ + export function link(oldpath: string, newpath: string): Promise; + + /** + * Synchronously creates `newpath` as a hard link to `oldpath`. + * + * ```ts + * Deno.linkSync("old/name", "new/name"); + * ``` + * + * Requires `allow-read` and `allow-write` permissions. + * + * @tags allow-read, allow-write + * @category File System + */ + export function linkSync(oldpath: string, newpath: string): void; + + /** + * A enum which defines the seek mode for IO related APIs that support + * seeking. + * + * @category I/O */ + export enum SeekMode { + /* Seek from the start of the file/resource. */ + Start = 0, + /* Seek from the current position within the file/resource. */ + Current = 1, + /* Seek from the end of the current file/resource. */ + End = 2, + } + + /** Open a file and resolve to an instance of {@linkcode Deno.FsFile}. The + * file does not need to previously exist if using the `create` or `createNew` + * open options. The caller may have the resulting file automatically closed + * by the runtime once it's out of scope by declaring the file variable with + * the `using` keyword. + * + * ```ts + * using file = await Deno.open("/foo/bar.txt", { read: true, write: true }); + * // Do work with file + * ``` + * + * Alternatively, the caller may manually close the resource when finished with + * it. + * + * ```ts + * const file = await Deno.open("/foo/bar.txt", { read: true, write: true }); + * // Do work with file + * file.close(); + * ``` + * + * Requires `allow-read` and/or `allow-write` permissions depending on + * options. + * + * @tags allow-read, allow-write + * @category File System + */ + export function open( + path: string | URL, + options?: OpenOptions, + ): Promise; + + /** Synchronously open a file and return an instance of + * {@linkcode Deno.FsFile}. The file does not need to previously exist if + * using the `create` or `createNew` open options. The caller may have the + * resulting file automatically closed by the runtime once it's out of scope + * by declaring the file variable with the `using` keyword. + * + * ```ts + * using file = Deno.openSync("/foo/bar.txt", { read: true, write: true }); + * // Do work with file + * ``` + * + * Alternatively, the caller may manually close the resource when finished with + * it. + * + * ```ts + * const file = Deno.openSync("/foo/bar.txt", { read: true, write: true }); + * // Do work with file + * file.close(); + * ``` + * + * Requires `allow-read` and/or `allow-write` permissions depending on + * options. + * + * @tags allow-read, allow-write + * @category File System + */ + export function openSync(path: string | URL, options?: OpenOptions): FsFile; + + /** Creates a file if none exists or truncates an existing file and resolves to + * an instance of {@linkcode Deno.FsFile}. + * + * ```ts + * const file = await Deno.create("/foo/bar.txt"); + * ``` + * + * Requires `allow-read` and `allow-write` permissions. + * + * @tags allow-read, allow-write + * @category File System + */ + export function create(path: string | URL): Promise; + + /** Creates a file if none exists or truncates an existing file and returns + * an instance of {@linkcode Deno.FsFile}. + * + * ```ts + * const file = Deno.createSync("/foo/bar.txt"); + * ``` + * + * Requires `allow-read` and `allow-write` permissions. + * + * @tags allow-read, allow-write + * @category File System + */ + export function createSync(path: string | URL): FsFile; + + /** The Deno abstraction for reading and writing files. + * + * This is the most straight forward way of handling files within Deno and is + * recommended over using the discrete functions within the `Deno` namespace. + * + * ```ts + * using file = await Deno.open("/foo/bar.txt", { read: true }); + * const fileInfo = await file.stat(); + * if (fileInfo.isFile) { + * const buf = new Uint8Array(100); + * const numberOfBytesRead = await file.read(buf); // 11 bytes + * const text = new TextDecoder().decode(buf); // "hello world" + * } + * ``` + * + * @category File System + */ + export class FsFile implements Disposable { + /** A {@linkcode ReadableStream} instance representing to the byte contents + * of the file. This makes it easy to interoperate with other web streams + * based APIs. + * + * ```ts + * using file = await Deno.open("my_file.txt", { read: true }); + * const decoder = new TextDecoder(); + * for await (const chunk of file.readable) { + * console.log(decoder.decode(chunk)); + * } + * ``` + */ + readonly readable: ReadableStream>; + /** A {@linkcode WritableStream} instance to write the contents of the + * file. This makes it easy to interoperate with other web streams based + * APIs. + * + * ```ts + * const items = ["hello", "world"]; + * using file = await Deno.open("my_file.txt", { write: true }); + * const encoder = new TextEncoder(); + * const writer = file.writable.getWriter(); + * for (const item of items) { + * await writer.write(encoder.encode(item)); + * } + * ``` + */ + readonly writable: WritableStream>; + /** Write the contents of the array buffer (`p`) to the file. + * + * Resolves to the number of bytes written. + * + * **It is not guaranteed that the full buffer will be written in a single + * call.** + * + * ```ts + * const encoder = new TextEncoder(); + * const data = encoder.encode("Hello world"); + * using file = await Deno.open("/foo/bar.txt", { write: true }); + * const bytesWritten = await file.write(data); // 11 + * ``` + * + * @category I/O + */ + write(p: Uint8Array): Promise; + /** Synchronously write the contents of the array buffer (`p`) to the file. + * + * Returns the number of bytes written. + * + * **It is not guaranteed that the full buffer will be written in a single + * call.** + * + * ```ts + * const encoder = new TextEncoder(); + * const data = encoder.encode("Hello world"); + * using file = Deno.openSync("/foo/bar.txt", { write: true }); + * const bytesWritten = file.writeSync(data); // 11 + * ``` + */ + writeSync(p: Uint8Array): number; + /** Truncates (or extends) the file to reach the specified `len`. If `len` + * is not specified, then the entire file contents are truncated. + * + * ### Truncate the entire file + * + * ```ts + * using file = await Deno.open("my_file.txt", { write: true }); + * await file.truncate(); + * ``` + * + * ### Truncate part of the file + * + * ```ts + * // if "my_file.txt" contains the text "hello world": + * using file = await Deno.open("my_file.txt", { write: true }); + * await file.truncate(7); + * const buf = new Uint8Array(100); + * await file.read(buf); + * const text = new TextDecoder().decode(buf); // "hello w" + * ``` + */ + truncate(len?: number): Promise; + /** Synchronously truncates (or extends) the file to reach the specified + * `len`. If `len` is not specified, then the entire file contents are + * truncated. + * + * ### Truncate the entire file + * + * ```ts + * using file = Deno.openSync("my_file.txt", { write: true }); + * file.truncateSync(); + * ``` + * + * ### Truncate part of the file + * + * ```ts + * // if "my_file.txt" contains the text "hello world": + * using file = Deno.openSync("my_file.txt", { write: true }); + * file.truncateSync(7); + * const buf = new Uint8Array(100); + * file.readSync(buf); + * const text = new TextDecoder().decode(buf); // "hello w" + * ``` + */ + truncateSync(len?: number): void; + /** Read the file into an array buffer (`p`). + * + * Resolves to either the number of bytes read during the operation or EOF + * (`null`) if there was nothing more to read. + * + * It is possible for a read to successfully return with `0` bytes. This + * does not indicate EOF. + * + * **It is not guaranteed that the full buffer will be read in a single + * call.** + * + * ```ts + * // if "/foo/bar.txt" contains the text "hello world": + * using file = await Deno.open("/foo/bar.txt"); + * const buf = new Uint8Array(100); + * const numberOfBytesRead = await file.read(buf); // 11 bytes + * const text = new TextDecoder().decode(buf); // "hello world" + * ``` + */ + read(p: Uint8Array): Promise; + /** Synchronously read from the file into an array buffer (`p`). + * + * Returns either the number of bytes read during the operation or EOF + * (`null`) if there was nothing more to read. + * + * It is possible for a read to successfully return with `0` bytes. This + * does not indicate EOF. + * + * **It is not guaranteed that the full buffer will be read in a single + * call.** + * + * ```ts + * // if "/foo/bar.txt" contains the text "hello world": + * using file = Deno.openSync("/foo/bar.txt"); + * const buf = new Uint8Array(100); + * const numberOfBytesRead = file.readSync(buf); // 11 bytes + * const text = new TextDecoder().decode(buf); // "hello world" + * ``` + */ + readSync(p: Uint8Array): number | null; + /** Seek to the given `offset` under mode given by `whence`. The call + * resolves to the new position within the resource (bytes from the start). + * + * ```ts + * // Given the file contains "Hello world" text, which is 11 bytes long: + * using file = await Deno.open( + * "hello.txt", + * { read: true, write: true, truncate: true, create: true }, + * ); + * await file.write(new TextEncoder().encode("Hello world")); + * + * // advance cursor 6 bytes + * const cursorPosition = await file.seek(6, Deno.SeekMode.Start); + * console.log(cursorPosition); // 6 + * const buf = new Uint8Array(100); + * await file.read(buf); + * console.log(new TextDecoder().decode(buf)); // "world" + * ``` + * + * The seek modes work as follows: + * + * ```ts + * // Given the file contains "Hello world" text, which is 11 bytes long: + * const file = await Deno.open( + * "hello.txt", + * { read: true, write: true, truncate: true, create: true }, + * ); + * await file.write(new TextEncoder().encode("Hello world")); + * + * // Seek 6 bytes from the start of the file + * console.log(await file.seek(6, Deno.SeekMode.Start)); // "6" + * // Seek 2 more bytes from the current position + * console.log(await file.seek(2, Deno.SeekMode.Current)); // "8" + * // Seek backwards 2 bytes from the end of the file + * console.log(await file.seek(-2, Deno.SeekMode.End)); // "9" (i.e. 11-2) + * ``` + */ + seek(offset: number | bigint, whence: SeekMode): Promise; + /** Synchronously seek to the given `offset` under mode given by `whence`. + * The new position within the resource (bytes from the start) is returned. + * + * ```ts + * using file = Deno.openSync( + * "hello.txt", + * { read: true, write: true, truncate: true, create: true }, + * ); + * file.writeSync(new TextEncoder().encode("Hello world")); + * + * // advance cursor 6 bytes + * const cursorPosition = file.seekSync(6, Deno.SeekMode.Start); + * console.log(cursorPosition); // 6 + * const buf = new Uint8Array(100); + * file.readSync(buf); + * console.log(new TextDecoder().decode(buf)); // "world" + * ``` + * + * The seek modes work as follows: + * + * ```ts + * // Given the file contains "Hello world" text, which is 11 bytes long: + * using file = Deno.openSync( + * "hello.txt", + * { read: true, write: true, truncate: true, create: true }, + * ); + * file.writeSync(new TextEncoder().encode("Hello world")); + * + * // Seek 6 bytes from the start of the file + * console.log(file.seekSync(6, Deno.SeekMode.Start)); // "6" + * // Seek 2 more bytes from the current position + * console.log(file.seekSync(2, Deno.SeekMode.Current)); // "8" + * // Seek backwards 2 bytes from the end of the file + * console.log(file.seekSync(-2, Deno.SeekMode.End)); // "9" (i.e. 11-2) + * ``` + */ + seekSync(offset: number | bigint, whence: SeekMode): number; + /** Resolves to a {@linkcode Deno.FileInfo} for the file. + * + * ```ts + * import { assert } from "jsr:@std/assert"; + * + * using file = await Deno.open("hello.txt"); + * const fileInfo = await file.stat(); + * assert(fileInfo.isFile); + * ``` + */ + stat(): Promise; + /** Synchronously returns a {@linkcode Deno.FileInfo} for the file. + * + * ```ts + * import { assert } from "jsr:@std/assert"; + * + * using file = Deno.openSync("hello.txt") + * const fileInfo = file.statSync(); + * assert(fileInfo.isFile); + * ``` + */ + statSync(): FileInfo; + /** + * Flushes any pending data and metadata operations of the given file + * stream to disk. + * + * ```ts + * const file = await Deno.open( + * "my_file.txt", + * { read: true, write: true, create: true }, + * ); + * await file.write(new TextEncoder().encode("Hello World")); + * await file.truncate(1); + * await file.sync(); + * console.log(await Deno.readTextFile("my_file.txt")); // H + * ``` + * + * @category I/O + */ + sync(): Promise; + /** + * Synchronously flushes any pending data and metadata operations of the given + * file stream to disk. + * + * ```ts + * const file = Deno.openSync( + * "my_file.txt", + * { read: true, write: true, create: true }, + * ); + * file.writeSync(new TextEncoder().encode("Hello World")); + * file.truncateSync(1); + * file.syncSync(); + * console.log(Deno.readTextFileSync("my_file.txt")); // H + * ``` + * + * @category I/O + */ + syncSync(): void; + /** + * Flushes any pending data operations of the given file stream to disk. + * ```ts + * using file = await Deno.open( + * "my_file.txt", + * { read: true, write: true, create: true }, + * ); + * await file.write(new TextEncoder().encode("Hello World")); + * await file.syncData(); + * console.log(await Deno.readTextFile("my_file.txt")); // Hello World + * ``` + * + * @category I/O + */ + syncData(): Promise; + /** + * Synchronously flushes any pending data operations of the given file stream + * to disk. + * + * ```ts + * using file = Deno.openSync( + * "my_file.txt", + * { read: true, write: true, create: true }, + * ); + * file.writeSync(new TextEncoder().encode("Hello World")); + * file.syncDataSync(); + * console.log(Deno.readTextFileSync("my_file.txt")); // Hello World + * ``` + * + * @category I/O + */ + syncDataSync(): void; + /** + * Changes the access (`atime`) and modification (`mtime`) times of the + * file stream resource. Given times are either in seconds (UNIX epoch + * time) or as `Date` objects. + * + * ```ts + * using file = await Deno.open("file.txt", { create: true, write: true }); + * await file.utime(1556495550, new Date()); + * ``` + * + * @category File System + */ + utime(atime: number | Date, mtime: number | Date): Promise; + /** + * Synchronously changes the access (`atime`) and modification (`mtime`) + * times of the file stream resource. Given times are either in seconds + * (UNIX epoch time) or as `Date` objects. + * + * ```ts + * using file = Deno.openSync("file.txt", { create: true, write: true }); + * file.utime(1556495550, new Date()); + * ``` + * + * @category File System + */ + utimeSync(atime: number | Date, mtime: number | Date): void; + /** **UNSTABLE**: New API, yet to be vetted. + * + * Checks if the file resource is a TTY (terminal). + * + * ```ts + * // This example is system and context specific + * using file = await Deno.open("/dev/tty6"); + * file.isTerminal(); // true + * ``` + */ + isTerminal(): boolean; + /** **UNSTABLE**: New API, yet to be vetted. + * + * Set TTY to be under raw mode or not. In raw mode, characters are read and + * returned as is, without being processed. All special processing of + * characters by the terminal is disabled, including echoing input + * characters. Reading from a TTY device in raw mode is faster than reading + * from a TTY device in canonical mode. + * + * ```ts + * using file = await Deno.open("/dev/tty6"); + * file.setRaw(true, { cbreak: true }); + * ``` + */ + setRaw(mode: boolean, options?: SetRawOptions): void; + /** + * Acquire an advisory file-system lock for the file. + * + * @param [exclusive=false] + */ + lock(exclusive?: boolean): Promise; + /** + * Synchronously acquire an advisory file-system lock synchronously for the file. + * + * @param [exclusive=false] + */ + lockSync(exclusive?: boolean): void; + /** + * Release an advisory file-system lock for the file. + */ + unlock(): Promise; + /** + * Synchronously release an advisory file-system lock for the file. + */ + unlockSync(): void; + /** Close the file. Closing a file when you are finished with it is + * important to avoid leaking resources. + * + * ```ts + * using file = await Deno.open("my_file.txt"); + * // do work with "file" object + * ``` + */ + close(): void; + + [Symbol.dispose](): void; + } + + /** Gets the size of the console as columns/rows. + * + * ```ts + * const { columns, rows } = Deno.consoleSize(); + * ``` + * + * This returns the size of the console window as reported by the operating + * system. It's not a reflection of how many characters will fit within the + * console window, but can be used as part of that calculation. + * + * @category I/O + */ + export function consoleSize(): { + columns: number; + rows: number; + }; + + /** @category I/O */ + export interface SetRawOptions { + /** + * The `cbreak` option can be used to indicate that characters that + * correspond to a signal should still be generated. When disabling raw + * mode, this option is ignored. This functionality currently only works on + * Linux and Mac OS. + */ + cbreak: boolean; + } + + /** A reference to `stdin` which can be used to read directly from `stdin`. + * + * It implements the Deno specific + * {@linkcode https://jsr.io/@std/io/doc/types/~/Reader | Reader}, + * {@linkcode https://jsr.io/@std/io/doc/types/~/ReaderSync | ReaderSync}, + * and {@linkcode https://jsr.io/@std/io/doc/types/~/Closer | Closer} + * interfaces as well as provides a {@linkcode ReadableStream} interface. + * + * ### Reading chunks from the readable stream + * + * ```ts + * const decoder = new TextDecoder(); + * for await (const chunk of Deno.stdin.readable) { + * const text = decoder.decode(chunk); + * // do something with the text + * } + * ``` + * + * @category I/O + */ + export const stdin: { + /** Read the incoming data from `stdin` into an array buffer (`p`). + * + * Resolves to either the number of bytes read during the operation or EOF + * (`null`) if there was nothing more to read. + * + * It is possible for a read to successfully return with `0` bytes. This + * does not indicate EOF. + * + * **It is not guaranteed that the full buffer will be read in a single + * call.** + * + * ```ts + * // If the text "hello world" is piped into the script: + * const buf = new Uint8Array(100); + * const numberOfBytesRead = await Deno.stdin.read(buf); // 11 bytes + * const text = new TextDecoder().decode(buf); // "hello world" + * ``` + * + * @category I/O + */ + read(p: Uint8Array): Promise; + /** Synchronously read from the incoming data from `stdin` into an array + * buffer (`p`). + * + * Returns either the number of bytes read during the operation or EOF + * (`null`) if there was nothing more to read. + * + * It is possible for a read to successfully return with `0` bytes. This + * does not indicate EOF. + * + * **It is not guaranteed that the full buffer will be read in a single + * call.** + * + * ```ts + * // If the text "hello world" is piped into the script: + * const buf = new Uint8Array(100); + * const numberOfBytesRead = Deno.stdin.readSync(buf); // 11 bytes + * const text = new TextDecoder().decode(buf); // "hello world" + * ``` + * + * @category I/O + */ + readSync(p: Uint8Array): number | null; + /** Closes `stdin`, freeing the resource. + * + * ```ts + * Deno.stdin.close(); + * ``` + */ + close(): void; + /** A readable stream interface to `stdin`. */ + readonly readable: ReadableStream>; + /** + * Set TTY to be under raw mode or not. In raw mode, characters are read and + * returned as is, without being processed. All special processing of + * characters by the terminal is disabled, including echoing input + * characters. Reading from a TTY device in raw mode is faster than reading + * from a TTY device in canonical mode. + * + * ```ts + * Deno.stdin.setRaw(true, { cbreak: true }); + * ``` + * + * @category I/O + */ + setRaw(mode: boolean, options?: SetRawOptions): void; + /** + * Checks if `stdin` is a TTY (terminal). + * + * ```ts + * // This example is system and context specific + * Deno.stdin.isTerminal(); // true + * ``` + * + * @category I/O + */ + isTerminal(): boolean; + }; + /** A reference to `stdout` which can be used to write directly to `stdout`. + * It implements the Deno specific + * {@linkcode https://jsr.io/@std/io/doc/types/~/Writer | Writer}, + * {@linkcode https://jsr.io/@std/io/doc/types/~/WriterSync | WriterSync}, + * and {@linkcode https://jsr.io/@std/io/doc/types/~/Closer | Closer} interfaces as well as provides a + * {@linkcode WritableStream} interface. + * + * These are low level constructs, and the {@linkcode console} interface is a + * more straight forward way to interact with `stdout` and `stderr`. + * + * @category I/O + */ + export const stdout: { + /** Write the contents of the array buffer (`p`) to `stdout`. + * + * Resolves to the number of bytes written. + * + * **It is not guaranteed that the full buffer will be written in a single + * call.** + * + * ```ts + * const encoder = new TextEncoder(); + * const data = encoder.encode("Hello world"); + * const bytesWritten = await Deno.stdout.write(data); // 11 + * ``` + * + * @category I/O + */ + write(p: Uint8Array): Promise; + /** Synchronously write the contents of the array buffer (`p`) to `stdout`. + * + * Returns the number of bytes written. + * + * **It is not guaranteed that the full buffer will be written in a single + * call.** + * + * ```ts + * const encoder = new TextEncoder(); + * const data = encoder.encode("Hello world"); + * const bytesWritten = Deno.stdout.writeSync(data); // 11 + * ``` + */ + writeSync(p: Uint8Array): number; + /** Closes `stdout`, freeing the resource. + * + * ```ts + * Deno.stdout.close(); + * ``` + */ + close(): void; + /** A writable stream interface to `stdout`. */ + readonly writable: WritableStream>; + /** + * Checks if `stdout` is a TTY (terminal). + * + * ```ts + * // This example is system and context specific + * Deno.stdout.isTerminal(); // true + * ``` + * + * @category I/O + */ + isTerminal(): boolean; + }; + /** A reference to `stderr` which can be used to write directly to `stderr`. + * It implements the Deno specific + * {@linkcode https://jsr.io/@std/io/doc/types/~/Writer | Writer}, + * {@linkcode https://jsr.io/@std/io/doc/types/~/WriterSync | WriterSync}, + * and {@linkcode https://jsr.io/@std/io/doc/types/~/Closer | Closer} interfaces as well as provides a + * {@linkcode WritableStream} interface. + * + * These are low level constructs, and the {@linkcode console} interface is a + * more straight forward way to interact with `stdout` and `stderr`. + * + * @category I/O + */ + export const stderr: { + /** Write the contents of the array buffer (`p`) to `stderr`. + * + * Resolves to the number of bytes written. + * + * **It is not guaranteed that the full buffer will be written in a single + * call.** + * + * ```ts + * const encoder = new TextEncoder(); + * const data = encoder.encode("Hello world"); + * const bytesWritten = await Deno.stderr.write(data); // 11 + * ``` + * + * @category I/O + */ + write(p: Uint8Array): Promise; + /** Synchronously write the contents of the array buffer (`p`) to `stderr`. + * + * Returns the number of bytes written. + * + * **It is not guaranteed that the full buffer will be written in a single + * call.** + * + * ```ts + * const encoder = new TextEncoder(); + * const data = encoder.encode("Hello world"); + * const bytesWritten = Deno.stderr.writeSync(data); // 11 + * ``` + */ + writeSync(p: Uint8Array): number; + /** Closes `stderr`, freeing the resource. + * + * ```ts + * Deno.stderr.close(); + * ``` + */ + close(): void; + /** A writable stream interface to `stderr`. */ + readonly writable: WritableStream>; + /** + * Checks if `stderr` is a TTY (terminal). + * + * ```ts + * // This example is system and context specific + * Deno.stderr.isTerminal(); // true + * ``` + * + * @category I/O + */ + isTerminal(): boolean; + }; + + /** + * Options which can be set when doing {@linkcode Deno.open} and + * {@linkcode Deno.openSync}. + * + * @category File System */ + export interface OpenOptions { + /** Sets the option for read access. This option, when `true`, means that + * the file should be read-able if opened. + * + * @default {true} */ + read?: boolean; + /** Sets the option for write access. This option, when `true`, means that + * the file should be write-able if opened. If the file already exists, + * any write calls on it will overwrite its contents, by default without + * truncating it. + * + * @default {false} */ + write?: boolean; + /** Sets the option for the append mode. This option, when `true`, means + * that writes will append to a file instead of overwriting previous + * contents. + * + * Note that setting `{ write: true, append: true }` has the same effect as + * setting only `{ append: true }`. + * + * @default {false} */ + append?: boolean; + /** Sets the option for truncating a previous file. If a file is + * successfully opened with this option set it will truncate the file to `0` + * size if it already exists. The file must be opened with write access + * for truncate to work. + * + * @default {false} */ + truncate?: boolean; + /** Sets the option to allow creating a new file, if one doesn't already + * exist at the specified path. Requires write or append access to be + * used. + * + * @default {false} */ + create?: boolean; + /** If set to `true`, no file, directory, or symlink is allowed to exist at + * the target location. Requires write or append access to be used. When + * createNew is set to `true`, create and truncate are ignored. + * + * @default {false} */ + createNew?: boolean; + /** Permissions to use if creating the file (defaults to `0o666`, before + * the process's umask). + * + * Ignored on Windows. */ + mode?: number; + } + + /** + * Options which can be set when using {@linkcode Deno.readFile} or + * {@linkcode Deno.readFileSync}. + * + * @category File System */ + export interface ReadFileOptions { + /** + * An abort signal to allow cancellation of the file read operation. + * If the signal becomes aborted the readFile operation will be stopped + * and the promise returned will be rejected with an AbortError. + */ + signal?: AbortSignal; + } + + /** + * Options which can be set when using {@linkcode Deno.mkdir} and + * {@linkcode Deno.mkdirSync}. + * + * @category File System */ + export interface MkdirOptions { + /** If set to `true`, means that any intermediate directories will also be + * created (as with the shell command `mkdir -p`). + * + * Intermediate directories are created with the same permissions. + * + * When recursive is set to `true`, succeeds silently (without changing any + * permissions) if a directory already exists at the path, or if the path + * is a symlink to an existing directory. + * + * @default {false} */ + recursive?: boolean; + /** Permissions to use when creating the directory (defaults to `0o777`, + * before the process's umask). + * + * Ignored on Windows. */ + mode?: number; + } + + /** Creates a new directory with the specified path. + * + * ```ts + * await Deno.mkdir("new_dir"); + * await Deno.mkdir("nested/directories", { recursive: true }); + * await Deno.mkdir("restricted_access_dir", { mode: 0o700 }); + * ``` + * + * Defaults to throwing error if the directory already exists. + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + export function mkdir( + path: string | URL, + options?: MkdirOptions, + ): Promise; + + /** Synchronously creates a new directory with the specified path. + * + * ```ts + * Deno.mkdirSync("new_dir"); + * Deno.mkdirSync("nested/directories", { recursive: true }); + * Deno.mkdirSync("restricted_access_dir", { mode: 0o700 }); + * ``` + * + * Defaults to throwing error if the directory already exists. + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + export function mkdirSync(path: string | URL, options?: MkdirOptions): void; + + /** + * Options which can be set when using {@linkcode Deno.makeTempDir}, + * {@linkcode Deno.makeTempDirSync}, {@linkcode Deno.makeTempFile}, and + * {@linkcode Deno.makeTempFileSync}. + * + * @category File System */ + export interface MakeTempOptions { + /** Directory where the temporary directory should be created (defaults to + * the env variable `TMPDIR`, or the system's default, usually `/tmp`). + * + * Note that if the passed `dir` is relative, the path returned by + * `makeTempFile()` and `makeTempDir()` will also be relative. Be mindful of + * this when changing working directory. */ + dir?: string; + /** String that should precede the random portion of the temporary + * directory's name. */ + prefix?: string; + /** String that should follow the random portion of the temporary + * directory's name. */ + suffix?: string; + } + + /** Creates a new temporary directory in the default directory for temporary + * files, unless `dir` is specified. Other optional options include + * prefixing and suffixing the directory name with `prefix` and `suffix` + * respectively. + * + * This call resolves to the full path to the newly created directory. + * + * Multiple programs calling this function simultaneously will create different + * directories. It is the caller's responsibility to remove the directory when + * no longer needed. + * + * ```ts + * const tempDirName0 = await Deno.makeTempDir(); // e.g. /tmp/2894ea76 + * const tempDirName1 = await Deno.makeTempDir({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d + * ``` + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + // TODO(ry) Doesn't check permissions. + export function makeTempDir(options?: MakeTempOptions): Promise; + + /** Synchronously creates a new temporary directory in the default directory + * for temporary files, unless `dir` is specified. Other optional options + * include prefixing and suffixing the directory name with `prefix` and + * `suffix` respectively. + * + * The full path to the newly created directory is returned. + * + * Multiple programs calling this function simultaneously will create different + * directories. It is the caller's responsibility to remove the directory when + * no longer needed. + * + * ```ts + * const tempDirName0 = Deno.makeTempDirSync(); // e.g. /tmp/2894ea76 + * const tempDirName1 = Deno.makeTempDirSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d + * ``` + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + // TODO(ry) Doesn't check permissions. + export function makeTempDirSync(options?: MakeTempOptions): string; + + /** Creates a new temporary file in the default directory for temporary + * files, unless `dir` is specified. + * + * Other options include prefixing and suffixing the directory name with + * `prefix` and `suffix` respectively. + * + * This call resolves to the full path to the newly created file. + * + * Multiple programs calling this function simultaneously will create + * different files. It is the caller's responsibility to remove the file when + * no longer needed. + * + * ```ts + * const tmpFileName0 = await Deno.makeTempFile(); // e.g. /tmp/419e0bf2 + * const tmpFileName1 = await Deno.makeTempFile({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098 + * ``` + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + export function makeTempFile(options?: MakeTempOptions): Promise; + + /** Synchronously creates a new temporary file in the default directory for + * temporary files, unless `dir` is specified. + * + * Other options include prefixing and suffixing the directory name with + * `prefix` and `suffix` respectively. + * + * The full path to the newly created file is returned. + * + * Multiple programs calling this function simultaneously will create + * different files. It is the caller's responsibility to remove the file when + * no longer needed. + * + * ```ts + * const tempFileName0 = Deno.makeTempFileSync(); // e.g. /tmp/419e0bf2 + * const tempFileName1 = Deno.makeTempFileSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098 + * ``` + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + export function makeTempFileSync(options?: MakeTempOptions): string; + + /** Changes the permission of a specific file/directory of specified path. + * Ignores the process's umask. + * + * ```ts + * await Deno.chmod("/path/to/file", 0o666); + * ``` + * + * The mode is a sequence of 3 octal numbers. The first/left-most number + * specifies the permissions for the owner. The second number specifies the + * permissions for the group. The last/right-most number specifies the + * permissions for others. For example, with a mode of 0o764, the owner (7) + * can read/write/execute, the group (6) can read/write and everyone else (4) + * can read only. + * + * | Number | Description | + * | ------ | ----------- | + * | 7 | read, write, and execute | + * | 6 | read and write | + * | 5 | read and execute | + * | 4 | read only | + * | 3 | write and execute | + * | 2 | write only | + * | 1 | execute only | + * | 0 | no permission | + * + * NOTE: This API currently throws on Windows + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + export function chmod(path: string | URL, mode: number): Promise; + + /** Synchronously changes the permission of a specific file/directory of + * specified path. Ignores the process's umask. + * + * ```ts + * Deno.chmodSync("/path/to/file", 0o666); + * ``` + * + * For a full description, see {@linkcode Deno.chmod}. + * + * NOTE: This API currently throws on Windows + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + export function chmodSync(path: string | URL, mode: number): void; + + /** Change owner of a regular file or directory. + * + * This functionality is not available on Windows. + * + * ```ts + * await Deno.chown("myFile.txt", 1000, 1002); + * ``` + * + * Requires `allow-write` permission. + * + * Throws Error (not implemented) if executed on Windows. + * + * @tags allow-write + * @category File System + * + * @param path path to the file + * @param uid user id (UID) of the new owner, or `null` for no change + * @param gid group id (GID) of the new owner, or `null` for no change + */ + export function chown( + path: string | URL, + uid: number | null, + gid: number | null, + ): Promise; + + /** Synchronously change owner of a regular file or directory. + * + * This functionality is not available on Windows. + * + * ```ts + * Deno.chownSync("myFile.txt", 1000, 1002); + * ``` + * + * Requires `allow-write` permission. + * + * Throws Error (not implemented) if executed on Windows. + * + * @tags allow-write + * @category File System + * + * @param path path to the file + * @param uid user id (UID) of the new owner, or `null` for no change + * @param gid group id (GID) of the new owner, or `null` for no change + */ + export function chownSync( + path: string | URL, + uid: number | null, + gid: number | null, + ): void; + + /** + * Options which can be set when using {@linkcode Deno.remove} and + * {@linkcode Deno.removeSync}. + * + * @category File System */ + export interface RemoveOptions { + /** If set to `true`, path will be removed even if it's a non-empty directory. + * + * @default {false} */ + recursive?: boolean; + } + + /** Removes the named file or directory. + * + * ```ts + * await Deno.remove("/path/to/empty_dir/or/file"); + * await Deno.remove("/path/to/populated_dir/or/file", { recursive: true }); + * ``` + * + * Throws error if permission denied, path not found, or path is a non-empty + * directory and the `recursive` option isn't set to `true`. + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + export function remove( + path: string | URL, + options?: RemoveOptions, + ): Promise; + + /** Synchronously removes the named file or directory. + * + * ```ts + * Deno.removeSync("/path/to/empty_dir/or/file"); + * Deno.removeSync("/path/to/populated_dir/or/file", { recursive: true }); + * ``` + * + * Throws error if permission denied, path not found, or path is a non-empty + * directory and the `recursive` option isn't set to `true`. + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + export function removeSync(path: string | URL, options?: RemoveOptions): void; + + /** Synchronously renames (moves) `oldpath` to `newpath`. Paths may be files or + * directories. If `newpath` already exists and is not a directory, + * `renameSync()` replaces it. OS-specific restrictions may apply when + * `oldpath` and `newpath` are in different directories. + * + * ```ts + * Deno.renameSync("old/path", "new/path"); + * ``` + * + * On Unix-like OSes, this operation does not follow symlinks at either path. + * + * It varies between platforms when the operation throws errors, and if so what + * they are. It's always an error to rename anything to a non-empty directory. + * + * Requires `allow-read` and `allow-write` permissions. + * + * @tags allow-read, allow-write + * @category File System + */ + export function renameSync( + oldpath: string | URL, + newpath: string | URL, + ): void; + + /** Renames (moves) `oldpath` to `newpath`. Paths may be files or directories. + * If `newpath` already exists and is not a directory, `rename()` replaces it. + * OS-specific restrictions may apply when `oldpath` and `newpath` are in + * different directories. + * + * ```ts + * await Deno.rename("old/path", "new/path"); + * ``` + * + * On Unix-like OSes, this operation does not follow symlinks at either path. + * + * It varies between platforms when the operation throws errors, and if so + * what they are. It's always an error to rename anything to a non-empty + * directory. + * + * Requires `allow-read` and `allow-write` permissions. + * + * @tags allow-read, allow-write + * @category File System + */ + export function rename( + oldpath: string | URL, + newpath: string | URL, + ): Promise; + + /** Asynchronously reads and returns the entire contents of a file as an UTF-8 + * decoded string. Reading a directory throws an error. + * + * ```ts + * const data = await Deno.readTextFile("hello.txt"); + * console.log(data); + * ``` + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category File System + */ + export function readTextFile( + path: string | URL, + options?: ReadFileOptions, + ): Promise; + + /** Synchronously reads and returns the entire contents of a file as an UTF-8 + * decoded string. Reading a directory throws an error. + * + * ```ts + * const data = Deno.readTextFileSync("hello.txt"); + * console.log(data); + * ``` + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category File System + */ + export function readTextFileSync(path: string | URL): string; + + /** Reads and resolves to the entire contents of a file as an array of bytes. + * `TextDecoder` can be used to transform the bytes to string if required. + * Rejects with an error when reading a directory. + * + * ```ts + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello.txt"); + * console.log(decoder.decode(data)); + * ``` + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category File System + */ + export function readFile( + path: string | URL, + options?: ReadFileOptions, + ): Promise>; + + /** Synchronously reads and returns the entire contents of a file as an array + * of bytes. `TextDecoder` can be used to transform the bytes to string if + * required. Throws an error when reading a directory. + * + * ```ts + * const decoder = new TextDecoder("utf-8"); + * const data = Deno.readFileSync("hello.txt"); + * console.log(decoder.decode(data)); + * ``` + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category File System + */ + export function readFileSync(path: string | URL): Uint8Array; + + /** Provides information about a file and is returned by + * {@linkcode Deno.stat}, {@linkcode Deno.lstat}, {@linkcode Deno.statSync}, + * and {@linkcode Deno.lstatSync} or from calling `stat()` and `statSync()` + * on an {@linkcode Deno.FsFile} instance. + * + * @category File System + */ + export interface FileInfo { + /** True if this is info for a regular file. Mutually exclusive to + * `FileInfo.isDirectory` and `FileInfo.isSymlink`. */ + isFile: boolean; + /** True if this is info for a regular directory. Mutually exclusive to + * `FileInfo.isFile` and `FileInfo.isSymlink`. */ + isDirectory: boolean; + /** True if this is info for a symlink. Mutually exclusive to + * `FileInfo.isFile` and `FileInfo.isDirectory`. */ + isSymlink: boolean; + /** The size of the file, in bytes. */ + size: number; + /** The last modification time of the file. This corresponds to the `mtime` + * field from `stat` on Linux/Mac OS and `ftLastWriteTime` on Windows. This + * may not be available on all platforms. */ + mtime: Date | null; + /** The last access time of the file. This corresponds to the `atime` + * field from `stat` on Unix and `ftLastAccessTime` on Windows. This may not + * be available on all platforms. */ + atime: Date | null; + /** The creation time of the file. This corresponds to the `birthtime` + * field from `stat` on Mac/BSD and `ftCreationTime` on Windows. This may + * not be available on all platforms. */ + birthtime: Date | null; + /** The last change time of the file. This corresponds to the `ctime` + * field from `stat` on Mac/BSD and `ChangeTime` on Windows. This may + * not be available on all platforms. */ + ctime: Date | null; + /** ID of the device containing the file. */ + dev: number; + /** Inode number. + * + * _Linux/Mac OS only._ */ + ino: number | null; + /** The underlying raw `st_mode` bits that contain the standard Unix + * permissions for this file/directory. + */ + mode: number | null; + /** Number of hard links pointing to this file. + * + * _Linux/Mac OS only._ */ + nlink: number | null; + /** User ID of the owner of this file. + * + * _Linux/Mac OS only._ */ + uid: number | null; + /** Group ID of the owner of this file. + * + * _Linux/Mac OS only._ */ + gid: number | null; + /** Device ID of this file. + * + * _Linux/Mac OS only._ */ + rdev: number | null; + /** Blocksize for filesystem I/O. + * + * _Linux/Mac OS only._ */ + blksize: number | null; + /** Number of blocks allocated to the file, in 512-byte units. + * + * _Linux/Mac OS only._ */ + blocks: number | null; + /** True if this is info for a block device. + * + * _Linux/Mac OS only._ */ + isBlockDevice: boolean | null; + /** True if this is info for a char device. + * + * _Linux/Mac OS only._ */ + isCharDevice: boolean | null; + /** True if this is info for a fifo. + * + * _Linux/Mac OS only._ */ + isFifo: boolean | null; + /** True if this is info for a socket. + * + * _Linux/Mac OS only._ */ + isSocket: boolean | null; + } + + /** Resolves to the absolute normalized path, with symbolic links resolved. + * + * ```ts + * // e.g. given /home/alice/file.txt and current directory /home/alice + * await Deno.symlink("file.txt", "symlink_file.txt"); + * const realPath = await Deno.realPath("./file.txt"); + * const realSymLinkPath = await Deno.realPath("./symlink_file.txt"); + * console.log(realPath); // outputs "/home/alice/file.txt" + * console.log(realSymLinkPath); // outputs "/home/alice/file.txt" + * ``` + * + * Requires `allow-read` permission for the target path. + * + * Also requires `allow-read` permission for the `CWD` if the target path is + * relative. + * + * @tags allow-read + * @category File System + */ + export function realPath(path: string | URL): Promise; + + /** Synchronously returns absolute normalized path, with symbolic links + * resolved. + * + * ```ts + * // e.g. given /home/alice/file.txt and current directory /home/alice + * Deno.symlinkSync("file.txt", "symlink_file.txt"); + * const realPath = Deno.realPathSync("./file.txt"); + * const realSymLinkPath = Deno.realPathSync("./symlink_file.txt"); + * console.log(realPath); // outputs "/home/alice/file.txt" + * console.log(realSymLinkPath); // outputs "/home/alice/file.txt" + * ``` + * + * Requires `allow-read` permission for the target path. + * + * Also requires `allow-read` permission for the `CWD` if the target path is + * relative. + * + * @tags allow-read + * @category File System + */ + export function realPathSync(path: string | URL): string; + + /** + * Information about a directory entry returned from {@linkcode Deno.readDir} + * and {@linkcode Deno.readDirSync}. + * + * @category File System */ + export interface DirEntry { + /** The file name of the entry. It is just the entity name and does not + * include the full path. */ + name: string; + /** True if this is info for a regular file. Mutually exclusive to + * `DirEntry.isDirectory` and `DirEntry.isSymlink`. */ + isFile: boolean; + /** True if this is info for a regular directory. Mutually exclusive to + * `DirEntry.isFile` and `DirEntry.isSymlink`. */ + isDirectory: boolean; + /** True if this is info for a symlink. Mutually exclusive to + * `DirEntry.isFile` and `DirEntry.isDirectory`. */ + isSymlink: boolean; + } + + /** Reads the directory given by `path` and returns an async iterable of + * {@linkcode Deno.DirEntry}. The order of entries is not guaranteed. + * + * ```ts + * for await (const dirEntry of Deno.readDir("/")) { + * console.log(dirEntry.name); + * } + * ``` + * + * Throws error if `path` is not a directory. + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category File System + */ + export function readDir(path: string | URL): AsyncIterable; + + /** Synchronously reads the directory given by `path` and returns an iterable + * of {@linkcode Deno.DirEntry}. The order of entries is not guaranteed. + * + * ```ts + * for (const dirEntry of Deno.readDirSync("/")) { + * console.log(dirEntry.name); + * } + * ``` + * + * Throws error if `path` is not a directory. + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category File System + */ + export function readDirSync(path: string | URL): IteratorObject; + + /** Copies the contents and permissions of one file to another specified path, + * by default creating a new file if needed, else overwriting. Fails if target + * path is a directory or is unwritable. + * + * ```ts + * await Deno.copyFile("from.txt", "to.txt"); + * ``` + * + * Requires `allow-read` permission on `fromPath`. + * + * Requires `allow-write` permission on `toPath`. + * + * @tags allow-read, allow-write + * @category File System + */ + export function copyFile( + fromPath: string | URL, + toPath: string | URL, + ): Promise; + + /** Synchronously copies the contents and permissions of one file to another + * specified path, by default creating a new file if needed, else overwriting. + * Fails if target path is a directory or is unwritable. + * + * ```ts + * Deno.copyFileSync("from.txt", "to.txt"); + * ``` + * + * Requires `allow-read` permission on `fromPath`. + * + * Requires `allow-write` permission on `toPath`. + * + * @tags allow-read, allow-write + * @category File System + */ + export function copyFileSync( + fromPath: string | URL, + toPath: string | URL, + ): void; + + /** Resolves to the full path destination of the named symbolic link. + * + * ```ts + * await Deno.symlink("./test.txt", "./test_link.txt"); + * const target = await Deno.readLink("./test_link.txt"); // full path of ./test.txt + * ``` + * + * Throws TypeError if called with a hard link. + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category File System + */ + export function readLink(path: string | URL): Promise; + + /** Synchronously returns the full path destination of the named symbolic + * link. + * + * ```ts + * Deno.symlinkSync("./test.txt", "./test_link.txt"); + * const target = Deno.readLinkSync("./test_link.txt"); // full path of ./test.txt + * ``` + * + * Throws TypeError if called with a hard link. + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category File System + */ + export function readLinkSync(path: string | URL): string; + + /** Resolves to a {@linkcode Deno.FileInfo} for the specified `path`. If + * `path` is a symlink, information for the symlink will be returned instead + * of what it points to. + * + * ```ts + * import { assert } from "jsr:@std/assert"; + * const fileInfo = await Deno.lstat("hello.txt"); + * assert(fileInfo.isFile); + * ``` + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category File System + */ + export function lstat(path: string | URL): Promise; + + /** Synchronously returns a {@linkcode Deno.FileInfo} for the specified + * `path`. If `path` is a symlink, information for the symlink will be + * returned instead of what it points to. + * + * ```ts + * import { assert } from "jsr:@std/assert"; + * const fileInfo = Deno.lstatSync("hello.txt"); + * assert(fileInfo.isFile); + * ``` + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category File System + */ + export function lstatSync(path: string | URL): FileInfo; + + /** Resolves to a {@linkcode Deno.FileInfo} for the specified `path`. Will + * always follow symlinks. + * + * ```ts + * import { assert } from "jsr:@std/assert"; + * const fileInfo = await Deno.stat("hello.txt"); + * assert(fileInfo.isFile); + * ``` + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category File System + */ + export function stat(path: string | URL): Promise; + + /** Synchronously returns a {@linkcode Deno.FileInfo} for the specified + * `path`. Will always follow symlinks. + * + * ```ts + * import { assert } from "jsr:@std/assert"; + * const fileInfo = Deno.statSync("hello.txt"); + * assert(fileInfo.isFile); + * ``` + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category File System + */ + export function statSync(path: string | URL): FileInfo; + + /** Options for writing to a file. + * + * @category File System + */ + export interface WriteFileOptions { + /** If set to `true`, will append to a file instead of overwriting previous + * contents. + * + * @default {false} */ + append?: boolean; + /** Sets the option to allow creating a new file, if one doesn't already + * exist at the specified path. + * + * @default {true} */ + create?: boolean; + /** If set to `true`, no file, directory, or symlink is allowed to exist at + * the target location. When createNew is set to `true`, `create` is ignored. + * + * @default {false} */ + createNew?: boolean; + /** Permissions always applied to file. */ + mode?: number; + /** An abort signal to allow cancellation of the file write operation. + * + * If the signal becomes aborted the write file operation will be stopped + * and the promise returned will be rejected with an {@linkcode AbortError}. + */ + signal?: AbortSignal; + } + + /** Write `data` to the given `path`, by default creating a new file if + * needed, else overwriting. + * + * ```ts + * const encoder = new TextEncoder(); + * const data = encoder.encode("Hello world\n"); + * await Deno.writeFile("hello1.txt", data); // overwrite "hello1.txt" or create it + * await Deno.writeFile("hello2.txt", data, { create: false }); // only works if "hello2.txt" exists + * await Deno.writeFile("hello3.txt", data, { mode: 0o777 }); // set permissions on new file + * await Deno.writeFile("hello4.txt", data, { append: true }); // add data to the end of the file + * ``` + * + * Requires `allow-write` permission, and `allow-read` if `options.create` is + * `false`. + * + * @tags allow-read, allow-write + * @category File System + */ + export function writeFile( + path: string | URL, + data: Uint8Array | ReadableStream, + options?: WriteFileOptions, + ): Promise; + + /** Synchronously write `data` to the given `path`, by default creating a new + * file if needed, else overwriting. + * + * ```ts + * const encoder = new TextEncoder(); + * const data = encoder.encode("Hello world\n"); + * Deno.writeFileSync("hello1.txt", data); // overwrite "hello1.txt" or create it + * Deno.writeFileSync("hello2.txt", data, { create: false }); // only works if "hello2.txt" exists + * Deno.writeFileSync("hello3.txt", data, { mode: 0o777 }); // set permissions on new file + * Deno.writeFileSync("hello4.txt", data, { append: true }); // add data to the end of the file + * ``` + * + * Requires `allow-write` permission, and `allow-read` if `options.create` is + * `false`. + * + * @tags allow-read, allow-write + * @category File System + */ + export function writeFileSync( + path: string | URL, + data: Uint8Array, + options?: WriteFileOptions, + ): void; + + /** Write string `data` to the given `path`, by default creating a new file if + * needed, else overwriting. + * + * ```ts + * await Deno.writeTextFile("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it + * ``` + * + * Requires `allow-write` permission, and `allow-read` if `options.create` is + * `false`. + * + * @tags allow-read, allow-write + * @category File System + */ + export function writeTextFile( + path: string | URL, + data: string | ReadableStream, + options?: WriteFileOptions, + ): Promise; + + /** Synchronously write string `data` to the given `path`, by default creating + * a new file if needed, else overwriting. + * + * ```ts + * Deno.writeTextFileSync("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it + * ``` + * + * Requires `allow-write` permission, and `allow-read` if `options.create` is + * `false`. + * + * @tags allow-read, allow-write + * @category File System + */ + export function writeTextFileSync( + path: string | URL, + data: string, + options?: WriteFileOptions, + ): void; + + /** Truncates (or extends) the specified file, to reach the specified `len`. + * If `len` is not specified then the entire file contents are truncated. + * + * ### Truncate the entire file + * ```ts + * await Deno.truncate("my_file.txt"); + * ``` + * + * ### Truncate part of the file + * + * ```ts + * const file = await Deno.makeTempFile(); + * await Deno.writeTextFile(file, "Hello World"); + * await Deno.truncate(file, 7); + * const data = await Deno.readFile(file); + * console.log(new TextDecoder().decode(data)); // "Hello W" + * ``` + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + export function truncate(name: string, len?: number): Promise; + + /** Synchronously truncates (or extends) the specified file, to reach the + * specified `len`. If `len` is not specified then the entire file contents + * are truncated. + * + * ### Truncate the entire file + * + * ```ts + * Deno.truncateSync("my_file.txt"); + * ``` + * + * ### Truncate part of the file + * + * ```ts + * const file = Deno.makeTempFileSync(); + * Deno.writeFileSync(file, new TextEncoder().encode("Hello World")); + * Deno.truncateSync(file, 7); + * const data = Deno.readFileSync(file); + * console.log(new TextDecoder().decode(data)); + * ``` + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + export function truncateSync(name: string, len?: number): void; + + /** @category Runtime + * + * @deprecated This will be removed in Deno 2.0. + */ + export interface OpMetrics { + opsDispatched: number; + opsDispatchedSync: number; + opsDispatchedAsync: number; + opsDispatchedAsyncUnref: number; + opsCompleted: number; + opsCompletedSync: number; + opsCompletedAsync: number; + opsCompletedAsyncUnref: number; + bytesSentControl: number; + bytesSentData: number; + bytesReceived: number; + } + + /** + * Additional information for FsEvent objects with the "other" kind. + * + * - `"rescan"`: rescan notices indicate either a lapse in the events or a + * change in the filesystem such that events received so far can no longer + * be relied on to represent the state of the filesystem now. An + * application that simply reacts to file changes may not care about this. + * An application that keeps an in-memory representation of the filesystem + * will need to care, and will need to refresh that representation directly + * from the filesystem. + * + * @category File System + */ + export type FsEventFlag = "rescan"; + + /** + * Represents a unique file system event yielded by a + * {@linkcode Deno.FsWatcher}. + * + * @category File System */ + export interface FsEvent { + /** The kind/type of the file system event. */ + kind: + | "any" + | "access" + | "create" + | "modify" + | "rename" + | "remove" + | "other"; + /** An array of paths that are associated with the file system event. */ + paths: string[]; + /** Any additional flags associated with the event. */ + flag?: FsEventFlag; + } + + /** + * Returned by {@linkcode Deno.watchFs}. It is an async iterator yielding up + * system events. To stop watching the file system by calling `.close()` + * method. + * + * @category File System + */ + export interface FsWatcher extends AsyncIterable, Disposable { + /** Stops watching the file system and closes the watcher resource. */ + close(): void; + /** + * Stops watching the file system and closes the watcher resource. + */ + return?(value?: any): Promise>; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + /** Watch for file system events against one or more `paths`, which can be + * files or directories. These paths must exist already. One user action (e.g. + * `touch test.file`) can generate multiple file system events. Likewise, + * one user action can result in multiple file paths in one event (e.g. `mv + * old_name.txt new_name.txt`). + * + * The recursive option is `true` by default and, for directories, will watch + * the specified directory and all sub directories. + * + * Note that the exact ordering of the events can vary between operating + * systems. + * + * ```ts + * const watcher = Deno.watchFs("/"); + * for await (const event of watcher) { + * console.log(">>>> event", event); + * // { kind: "create", paths: [ "/foo.txt" ] } + * } + * ``` + * + * Call `watcher.close()` to stop watching. + * + * ```ts + * const watcher = Deno.watchFs("/"); + * + * setTimeout(() => { + * watcher.close(); + * }, 5000); + * + * for await (const event of watcher) { + * console.log(">>>> event", event); + * } + * ``` + * + * Requires `allow-read` permission. + * + * @tags allow-read + * @category File System + */ + export function watchFs( + paths: string | string[], + options?: { recursive: boolean }, + ): FsWatcher; + + /** Operating signals which can be listened for or sent to sub-processes. What + * signals and what their standard behaviors are OS dependent. + * + * @category Runtime */ + export type Signal = + | "SIGABRT" + | "SIGALRM" + | "SIGBREAK" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGEMT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINFO" + | "SIGINT" + | "SIGIO" + | "SIGPOLL" + | "SIGUNUSED" + | "SIGKILL" + | "SIGPIPE" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ"; + + /** Registers the given function as a listener of the given signal event. + * + * ```ts + * Deno.addSignalListener( + * "SIGTERM", + * () => { + * console.log("SIGTERM!") + * } + * ); + * ``` + * + * _Note_: On Windows only `"SIGINT"` (CTRL+C) and `"SIGBREAK"` (CTRL+Break) + * are supported. + * + * @category Runtime + */ + export function addSignalListener(signal: Signal, handler: () => void): void; + + /** Removes the given signal listener that has been registered with + * {@linkcode Deno.addSignalListener}. + * + * ```ts + * const listener = () => { + * console.log("SIGTERM!") + * }; + * Deno.addSignalListener("SIGTERM", listener); + * Deno.removeSignalListener("SIGTERM", listener); + * ``` + * + * _Note_: On Windows only `"SIGINT"` (CTRL+C) and `"SIGBREAK"` (CTRL+Break) + * are supported. + * + * @category Runtime + */ + export function removeSignalListener( + signal: Signal, + handler: () => void, + ): void; + + /** Create a child process. + * + * If any stdio options are not set to `"piped"`, accessing the corresponding + * field on the `Command` or its `CommandOutput` will throw a `TypeError`. + * + * If `stdin` is set to `"piped"`, the `stdin` {@linkcode WritableStream} + * needs to be closed manually. + * + * `Command` acts as a builder. Each call to {@linkcode Command.spawn} or + * {@linkcode Command.output} will spawn a new subprocess. + * + * @example Spawn a subprocess and pipe the output to a file + * + * ```ts + * const command = new Deno.Command(Deno.execPath(), { + * args: [ + * "eval", + * "console.log('Hello World')", + * ], + * stdin: "piped", + * stdout: "piped", + * }); + * const child = command.spawn(); + * + * // open a file and pipe the subprocess output to it. + * child.stdout.pipeTo( + * Deno.openSync("output", { write: true, create: true }).writable, + * ); + * + * // manually close stdin + * child.stdin.close(); + * const status = await child.status; + * ``` + * + * @example Spawn a subprocess and collect its output + * + * ```ts + * const command = new Deno.Command(Deno.execPath(), { + * args: [ + * "eval", + * "console.log('hello'); console.error('world')", + * ], + * }); + * const { code, stdout, stderr } = await command.output(); + * console.assert(code === 0); + * console.assert("hello\n" === new TextDecoder().decode(stdout)); + * console.assert("world\n" === new TextDecoder().decode(stderr)); + * ``` + * + * @example Spawn a subprocess and collect its output synchronously + * + * ```ts + * const command = new Deno.Command(Deno.execPath(), { + * args: [ + * "eval", + * "console.log('hello'); console.error('world')", + * ], + * }); + * const { code, stdout, stderr } = command.outputSync(); + * console.assert(code === 0); + * console.assert("hello\n" === new TextDecoder().decode(stdout)); + * console.assert("world\n" === new TextDecoder().decode(stderr)); + * ``` + * + * @tags allow-run + * @category Subprocess + */ + export class Command { + constructor(command: string | URL, options?: CommandOptions); + /** + * Executes the {@linkcode Deno.Command}, waiting for it to finish and + * collecting all of its output. + * + * Will throw an error if `stdin: "piped"` is set. + * + * If options `stdout` or `stderr` are not set to `"piped"`, accessing the + * corresponding field on {@linkcode Deno.CommandOutput} will throw a `TypeError`. + */ + output(): Promise; + /** + * Synchronously executes the {@linkcode Deno.Command}, waiting for it to + * finish and collecting all of its output. + * + * Will throw an error if `stdin: "piped"` is set. + * + * If options `stdout` or `stderr` are not set to `"piped"`, accessing the + * corresponding field on {@linkcode Deno.CommandOutput} will throw a `TypeError`. + */ + outputSync(): CommandOutput; + /** + * Spawns a streamable subprocess, allowing to use the other methods. + */ + spawn(): ChildProcess; + } + + /** + * The interface for handling a child process returned from + * {@linkcode Deno.Command.spawn}. + * + * @category Subprocess + */ + export class ChildProcess implements AsyncDisposable { + get stdin(): WritableStream>; + get stdout(): ReadableStream>; + get stderr(): ReadableStream>; + readonly pid: number; + /** Get the status of the child. */ + readonly status: Promise; + + /** Waits for the child to exit completely, returning all its output and + * status. */ + output(): Promise; + /** Kills the process with given {@linkcode Deno.Signal}. + * + * Defaults to `SIGTERM` if no signal is provided. + * + * @param [signo="SIGTERM"] + */ + kill(signo?: Signal): void; + + /** Ensure that the status of the child process prevents the Deno process + * from exiting. */ + ref(): void; + /** Ensure that the status of the child process does not block the Deno + * process from exiting. */ + unref(): void; + + [Symbol.asyncDispose](): Promise; + } + + /** + * Options which can be set when calling {@linkcode Deno.Command}. + * + * @category Subprocess + */ + export interface CommandOptions { + /** Arguments to pass to the process. */ + args?: string[]; + /** + * The working directory of the process. + * + * If not specified, the `cwd` of the parent process is used. + */ + cwd?: string | URL; + /** + * Clear environmental variables from parent process. + * + * Doesn't guarantee that only `env` variables are present, as the OS may + * set environmental variables for processes. + * + * @default {false} + */ + clearEnv?: boolean; + /** Environmental variables to pass to the subprocess. */ + env?: Record; + /** + * Sets the child process’s user ID. This translates to a setuid call in the + * child process. Failure in the set uid call will cause the spawn to fail. + */ + uid?: number; + /** Similar to `uid`, but sets the group ID of the child process. */ + gid?: number; + /** + * An {@linkcode AbortSignal} that allows closing the process using the + * corresponding {@linkcode AbortController} by sending the process a + * SIGTERM signal. + * + * Not supported in {@linkcode Deno.Command.outputSync}. + */ + signal?: AbortSignal; + + /** How `stdin` of the spawned process should be handled. + * + * Defaults to `"inherit"` for `output` & `outputSync`, + * and `"inherit"` for `spawn`. */ + stdin?: "piped" | "inherit" | "null"; + /** How `stdout` of the spawned process should be handled. + * + * Defaults to `"piped"` for `output` & `outputSync`, + * and `"inherit"` for `spawn`. */ + stdout?: "piped" | "inherit" | "null"; + /** How `stderr` of the spawned process should be handled. + * + * Defaults to `"piped"` for `output` & `outputSync`, + * and `"inherit"` for `spawn`. */ + stderr?: "piped" | "inherit" | "null"; + + /** Skips quoting and escaping of the arguments on windows. This option + * is ignored on non-windows platforms. + * + * @default {false} */ + windowsRawArguments?: boolean; + } + + /** + * @category Subprocess + */ + export interface CommandStatus { + /** If the child process exits with a 0 status code, `success` will be set + * to `true`, otherwise `false`. */ + success: boolean; + /** The exit code of the child process. */ + code: number; + /** The signal associated with the child process. */ + signal: Signal | null; + } + + /** + * The interface returned from calling {@linkcode Deno.Command.output} or + * {@linkcode Deno.Command.outputSync} which represents the result of spawning the + * child process. + * + * @category Subprocess + */ + export interface CommandOutput extends CommandStatus { + /** The buffered output from the child process' `stdout`. */ + readonly stdout: Uint8Array; + /** The buffered output from the child process' `stderr`. */ + readonly stderr: Uint8Array; + } + + /** Option which can be specified when performing {@linkcode Deno.inspect}. + * + * @category I/O */ + export interface InspectOptions { + /** Stylize output with ANSI colors. + * + * @default {false} */ + colors?: boolean; + /** Try to fit more than one entry of a collection on the same line. + * + * @default {true} */ + compact?: boolean; + /** Traversal depth for nested objects. + * + * @default {4} */ + depth?: number; + /** The maximum length for an inspection to take up a single line. + * + * @default {80} */ + breakLength?: number; + /** Whether or not to escape sequences. + * + * @default {true} */ + escapeSequences?: boolean; + /** The maximum number of iterable entries to print. + * + * @default {100} */ + iterableLimit?: number; + /** Show a Proxy's target and handler. + * + * @default {false} */ + showProxy?: boolean; + /** Sort Object, Set and Map entries by key. + * + * @default {false} */ + sorted?: boolean; + /** Add a trailing comma for multiline collections. + * + * @default {false} */ + trailingComma?: boolean; + /** Evaluate the result of calling getters. + * + * @default {false} */ + getters?: boolean; + /** Show an object's non-enumerable properties. + * + * @default {false} */ + showHidden?: boolean; + /** The maximum length of a string before it is truncated with an + * ellipsis. */ + strAbbreviateSize?: number; + } + + /** Converts the input into a string that has the same format as printed by + * `console.log()`. + * + * ```ts + * const obj = { + * a: 10, + * b: "hello", + * }; + * const objAsString = Deno.inspect(obj); // { a: 10, b: "hello" } + * console.log(obj); // prints same value as objAsString, e.g. { a: 10, b: "hello" } + * ``` + * + * A custom inspect functions can be registered on objects, via the symbol + * `Symbol.for("Deno.customInspect")`, to control and customize the output + * of `inspect()` or when using `console` logging: + * + * ```ts + * class A { + * x = 10; + * y = "hello"; + * [Symbol.for("Deno.customInspect")]() { + * return `x=${this.x}, y=${this.y}`; + * } + * } + * + * const inStringFormat = Deno.inspect(new A()); // "x=10, y=hello" + * console.log(inStringFormat); // prints "x=10, y=hello" + * ``` + * + * A depth can be specified by using the `depth` option: + * + * ```ts + * Deno.inspect({a: {b: {c: {d: 'hello'}}}}, {depth: 2}); // { a: { b: [Object] } } + * ``` + * + * @category I/O + */ + export function inspect(value: unknown, options?: InspectOptions): string; + + /** The name of a privileged feature which needs permission. + * + * @category Permissions + */ + export type PermissionName = + | "run" + | "read" + | "write" + | "net" + | "env" + | "sys" + | "ffi"; + + /** The current status of the permission: + * + * - `"granted"` - the permission has been granted. + * - `"denied"` - the permission has been explicitly denied. + * - `"prompt"` - the permission has not explicitly granted nor denied. + * + * @category Permissions + */ + export type PermissionState = "granted" | "denied" | "prompt"; + + /** The permission descriptor for the `allow-run` and `deny-run` permissions, which controls + * access to what sub-processes can be executed by Deno. The option `command` + * allows scoping the permission to a specific executable. + * + * **Warning, in practice, `allow-run` is effectively the same as `allow-all` + * in the sense that malicious code could execute any arbitrary code on the + * host.** + * + * @category Permissions */ + export interface RunPermissionDescriptor { + name: "run"; + /** An `allow-run` or `deny-run` permission can be scoped to a specific executable, + * which would be relative to the start-up CWD of the Deno CLI. */ + command?: string | URL; + } + + /** The permission descriptor for the `allow-read` and `deny-read` permissions, which controls + * access to reading resources from the local host. The option `path` allows + * scoping the permission to a specific path (and if the path is a directory + * any sub paths). + * + * Permission granted under `allow-read` only allows runtime code to attempt + * to read, the underlying operating system may apply additional permissions. + * + * @category Permissions */ + export interface ReadPermissionDescriptor { + name: "read"; + /** An `allow-read` or `deny-read` permission can be scoped to a specific path (and if + * the path is a directory, any sub paths). */ + path?: string | URL; + } + + /** The permission descriptor for the `allow-write` and `deny-write` permissions, which + * controls access to writing to resources from the local host. The option + * `path` allow scoping the permission to a specific path (and if the path is + * a directory any sub paths). + * + * Permission granted under `allow-write` only allows runtime code to attempt + * to write, the underlying operating system may apply additional permissions. + * + * @category Permissions */ + export interface WritePermissionDescriptor { + name: "write"; + /** An `allow-write` or `deny-write` permission can be scoped to a specific path (and if + * the path is a directory, any sub paths). */ + path?: string | URL; + } + + /** The permission descriptor for the `allow-net` and `deny-net` permissions, which controls + * access to opening network ports and connecting to remote hosts via the + * network. The option `host` allows scoping the permission for outbound + * connection to a specific host and port. + * + * @category Permissions */ + export interface NetPermissionDescriptor { + name: "net"; + /** Optional host string of the form `"[:]"`. Examples: + * + * "github.com" + * "deno.land:8080" + */ + host?: string; + } + + /** The permission descriptor for the `allow-env` and `deny-env` permissions, which controls + * access to being able to read and write to the process environment variables + * as well as access other information about the environment. The option + * `variable` allows scoping the permission to a specific environment + * variable. + * + * @category Permissions */ + export interface EnvPermissionDescriptor { + name: "env"; + /** Optional environment variable name (e.g. `PATH`). */ + variable?: string; + } + + /** The permission descriptor for the `allow-sys` and `deny-sys` permissions, which controls + * access to sensitive host system information, which malicious code might + * attempt to exploit. The option `kind` allows scoping the permission to a + * specific piece of information. + * + * @category Permissions */ + export interface SysPermissionDescriptor { + name: "sys"; + /** The specific information to scope the permission to. */ + kind?: + | "loadavg" + | "hostname" + | "systemMemoryInfo" + | "networkInterfaces" + | "osRelease" + | "osUptime" + | "uid" + | "gid" + | "username" + | "cpus" + | "homedir" + | "statfs" + | "getPriority" + | "setPriority"; + } + + /** The permission descriptor for the `allow-ffi` and `deny-ffi` permissions, which controls + * access to loading _foreign_ code and interfacing with it via the + * [Foreign Function Interface API](https://docs.deno.com/runtime/manual/runtime/ffi_api) + * available in Deno. The option `path` allows scoping the permission to a + * specific path on the host. + * + * @category Permissions */ + export interface FfiPermissionDescriptor { + name: "ffi"; + /** Optional path on the local host to scope the permission to. */ + path?: string | URL; + } + + /** Permission descriptors which define a permission and can be queried, + * requested, or revoked. + * + * View the specifics of the individual descriptors for more information about + * each permission kind. + * + * @category Permissions + */ + export type PermissionDescriptor = + | RunPermissionDescriptor + | ReadPermissionDescriptor + | WritePermissionDescriptor + | NetPermissionDescriptor + | EnvPermissionDescriptor + | SysPermissionDescriptor + | FfiPermissionDescriptor; + + /** The interface which defines what event types are supported by + * {@linkcode PermissionStatus} instances. + * + * @category Permissions */ + export interface PermissionStatusEventMap { + change: Event; + } + + /** An {@linkcode EventTarget} returned from the {@linkcode Deno.permissions} + * API which can provide updates to any state changes of the permission. + * + * @category Permissions */ + export class PermissionStatus extends EventTarget { + // deno-lint-ignore no-explicit-any + onchange: ((this: PermissionStatus, ev: Event) => any) | null; + readonly state: PermissionState; + /** + * Describes if permission is only granted partially, eg. an access + * might be granted to "/foo" directory, but denied for "/foo/bar". + * In such case this field will be set to `true` when querying for + * read permissions of "/foo" directory. + */ + readonly partial: boolean; + addEventListener( + type: K, + listener: ( + this: PermissionStatus, + ev: PermissionStatusEventMap[K], + ) => any, + options?: boolean | AddEventListenerOptions, + ): void; + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void; + removeEventListener( + type: K, + listener: ( + this: PermissionStatus, + ev: PermissionStatusEventMap[K], + ) => any, + options?: boolean | EventListenerOptions, + ): void; + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions, + ): void; + } + + /** + * Deno's permission management API. + * + * The class which provides the interface for the {@linkcode Deno.permissions} + * global instance and is based on the web platform + * [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API), + * though some proposed parts of the API which are useful in a server side + * runtime context were removed or abandoned in the web platform specification + * which is why it was chosen to locate it in the {@linkcode Deno} namespace + * instead. + * + * By default, if the `stdin`/`stdout` is TTY for the Deno CLI (meaning it can + * send and receive text), then the CLI will prompt the user to grant + * permission when an un-granted permission is requested. This behavior can + * be changed by using the `--no-prompt` command at startup. When prompting + * the CLI will request the narrowest permission possible, potentially making + * it annoying to the user. The permissions APIs allow the code author to + * request a wider set of permissions at one time in order to provide a better + * user experience. + * + * @category Permissions */ + export class Permissions { + /** Resolves to the current status of a permission. + * + * Note, if the permission is already granted, `request()` will not prompt + * the user again, therefore `query()` is only necessary if you are going + * to react differently existing permissions without wanting to modify them + * or prompt the user to modify them. + * + * ```ts + * const status = await Deno.permissions.query({ name: "read", path: "/etc" }); + * console.log(status.state); + * ``` + */ + query(desc: PermissionDescriptor): Promise; + + /** Returns the current status of a permission. + * + * Note, if the permission is already granted, `request()` will not prompt + * the user again, therefore `querySync()` is only necessary if you are going + * to react differently existing permissions without wanting to modify them + * or prompt the user to modify them. + * + * ```ts + * const status = Deno.permissions.querySync({ name: "read", path: "/etc" }); + * console.log(status.state); + * ``` + */ + querySync(desc: PermissionDescriptor): PermissionStatus; + + /** Revokes a permission, and resolves to the state of the permission. + * + * ```ts + * import { assert } from "jsr:@std/assert"; + * + * const status = await Deno.permissions.revoke({ name: "run" }); + * assert(status.state !== "granted") + * ``` + */ + revoke(desc: PermissionDescriptor): Promise; + + /** Revokes a permission, and returns the state of the permission. + * + * ```ts + * import { assert } from "jsr:@std/assert"; + * + * const status = Deno.permissions.revokeSync({ name: "run" }); + * assert(status.state !== "granted") + * ``` + */ + revokeSync(desc: PermissionDescriptor): PermissionStatus; + + /** Requests the permission, and resolves to the state of the permission. + * + * If the permission is already granted, the user will not be prompted to + * grant the permission again. + * + * ```ts + * const status = await Deno.permissions.request({ name: "env" }); + * if (status.state === "granted") { + * console.log("'env' permission is granted."); + * } else { + * console.log("'env' permission is denied."); + * } + * ``` + */ + request(desc: PermissionDescriptor): Promise; + + /** Requests the permission, and returns the state of the permission. + * + * If the permission is already granted, the user will not be prompted to + * grant the permission again. + * + * ```ts + * const status = Deno.permissions.requestSync({ name: "env" }); + * if (status.state === "granted") { + * console.log("'env' permission is granted."); + * } else { + * console.log("'env' permission is denied."); + * } + * ``` + */ + requestSync(desc: PermissionDescriptor): PermissionStatus; + } + + /** Deno's permission management API. + * + * It is a singleton instance of the {@linkcode Permissions} object and is + * based on the web platform + * [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API), + * though some proposed parts of the API which are useful in a server side + * runtime context were removed or abandoned in the web platform specification + * which is why it was chosen to locate it in the {@linkcode Deno} namespace + * instead. + * + * By default, if the `stdin`/`stdout` is TTY for the Deno CLI (meaning it can + * send and receive text), then the CLI will prompt the user to grant + * permission when an un-granted permission is requested. This behavior can + * be changed by using the `--no-prompt` command at startup. When prompting + * the CLI will request the narrowest permission possible, potentially making + * it annoying to the user. The permissions APIs allow the code author to + * request a wider set of permissions at one time in order to provide a better + * user experience. + * + * Requesting already granted permissions will not prompt the user and will + * return that the permission was granted. + * + * ### Querying + * + * ```ts + * const status = await Deno.permissions.query({ name: "read", path: "/etc" }); + * console.log(status.state); + * ``` + * + * ```ts + * const status = Deno.permissions.querySync({ name: "read", path: "/etc" }); + * console.log(status.state); + * ``` + * + * ### Revoking + * + * ```ts + * import { assert } from "jsr:@std/assert"; + * + * const status = await Deno.permissions.revoke({ name: "run" }); + * assert(status.state !== "granted") + * ``` + * + * ```ts + * import { assert } from "jsr:@std/assert"; + * + * const status = Deno.permissions.revokeSync({ name: "run" }); + * assert(status.state !== "granted") + * ``` + * + * ### Requesting + * + * ```ts + * const status = await Deno.permissions.request({ name: "env" }); + * if (status.state === "granted") { + * console.log("'env' permission is granted."); + * } else { + * console.log("'env' permission is denied."); + * } + * ``` + * + * ```ts + * const status = Deno.permissions.requestSync({ name: "env" }); + * if (status.state === "granted") { + * console.log("'env' permission is granted."); + * } else { + * console.log("'env' permission is denied."); + * } + * ``` + * + * @category Permissions + */ + export const permissions: Permissions; + + /** Information related to the build of the current Deno runtime. + * + * Users are discouraged from code branching based on this information, as + * assumptions about what is available in what build environment might change + * over time. Developers should specifically sniff out the features they + * intend to use. + * + * The intended use for the information is for logging and debugging purposes. + * + * @category Runtime + */ + export const build: { + /** The [LLVM](https://llvm.org/) target triple, which is the combination + * of `${arch}-${vendor}-${os}` and represent the specific build target that + * the current runtime was built for. */ + target: string; + /** Instruction set architecture that the Deno CLI was built for. */ + arch: "x86_64" | "aarch64"; + /** The operating system that the Deno CLI was built for. `"darwin"` is + * also known as OSX or MacOS. */ + os: + | "darwin" + | "linux" + | "android" + | "windows" + | "freebsd" + | "netbsd" + | "aix" + | "solaris" + | "illumos"; + /** The computer vendor that the Deno CLI was built for. */ + vendor: string; + /** Optional environment flags that were set for this build of Deno CLI. */ + env?: string; + }; + + /** Version information related to the current Deno CLI runtime environment. + * + * Users are discouraged from code branching based on this information, as + * assumptions about what is available in what build environment might change + * over time. Developers should specifically sniff out the features they + * intend to use. + * + * The intended use for the information is for logging and debugging purposes. + * + * @category Runtime + */ + export const version: { + /** Deno CLI's version. For example: `"1.26.0"`. */ + deno: string; + /** The V8 version used by Deno. For example: `"10.7.100.0"`. + * + * V8 is the underlying JavaScript runtime platform that Deno is built on + * top of. */ + v8: string; + /** The TypeScript version used by Deno. For example: `"4.8.3"`. + * + * A version of the TypeScript type checker and language server is built-in + * to the Deno CLI. */ + typescript: string; + }; + + /** Returns the script arguments to the program. + * + * Give the following command line invocation of Deno: + * + * ```sh + * deno run --allow-read https://examples.deno.land/command-line-arguments.ts Sushi + * ``` + * + * Then `Deno.args` will contain: + * + * ```ts + * [ "Sushi" ] + * ``` + * + * If you are looking for a structured way to parse arguments, there is + * [`parseArgs()`](https://jsr.io/@std/cli/doc/parse-args/~/parseArgs) from + * the Deno Standard Library. + * + * @category Runtime + */ + export const args: string[]; + + /** The URL of the entrypoint module entered from the command-line. It + * requires read permission to the CWD. + * + * Also see {@linkcode ImportMeta} for other related information. + * + * @tags allow-read + * @category Runtime + */ + export const mainModule: string; + + /** Options that can be used with {@linkcode symlink} and + * {@linkcode symlinkSync}. + * + * @category File System */ + export interface SymlinkOptions { + /** Specify the symbolic link type as file, directory or NTFS junction. This + * option only applies to Windows and is ignored on other operating systems. */ + type: "file" | "dir" | "junction"; + } + + /** + * Creates `newpath` as a symbolic link to `oldpath`. + * + * The `options.type` parameter can be set to `"file"`, `"dir"` or `"junction"`. + * This argument is only available on Windows and ignored on other platforms. + * + * ```ts + * await Deno.symlink("old/name", "new/name"); + * ``` + * + * Requires full `allow-read` and `allow-write` permissions. + * + * @tags allow-read, allow-write + * @category File System + */ + export function symlink( + oldpath: string | URL, + newpath: string | URL, + options?: SymlinkOptions, + ): Promise; + + /** + * Creates `newpath` as a symbolic link to `oldpath`. + * + * The `options.type` parameter can be set to `"file"`, `"dir"` or `"junction"`. + * This argument is only available on Windows and ignored on other platforms. + * + * ```ts + * Deno.symlinkSync("old/name", "new/name"); + * ``` + * + * Requires full `allow-read` and `allow-write` permissions. + * + * @tags allow-read, allow-write + * @category File System + */ + export function symlinkSync( + oldpath: string | URL, + newpath: string | URL, + options?: SymlinkOptions, + ): void; + + /** + * Synchronously changes the access (`atime`) and modification (`mtime`) times + * of a file system object referenced by `path`. Given times are either in + * seconds (UNIX epoch time) or as `Date` objects. + * + * ```ts + * Deno.utimeSync("myfile.txt", 1556495550, new Date()); + * ``` + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + export function utimeSync( + path: string | URL, + atime: number | Date, + mtime: number | Date, + ): void; + + /** + * Changes the access (`atime`) and modification (`mtime`) times of a file + * system object referenced by `path`. Given times are either in seconds + * (UNIX epoch time) or as `Date` objects. + * + * ```ts + * await Deno.utime("myfile.txt", 1556495550, new Date()); + * ``` + * + * Requires `allow-write` permission. + * + * @tags allow-write + * @category File System + */ + export function utime( + path: string | URL, + atime: number | Date, + mtime: number | Date, + ): Promise; + + /** Retrieve the process umask. If `mask` is provided, sets the process umask. + * This call always returns what the umask was before the call. + * + * ```ts + * console.log(Deno.umask()); // e.g. 18 (0o022) + * const prevUmaskValue = Deno.umask(0o077); // e.g. 18 (0o022) + * console.log(Deno.umask()); // e.g. 63 (0o077) + * ``` + * + * This API is under consideration to determine if permissions are required to + * call it. + * + * *Note*: This API is not implemented on Windows + * + * @category File System + */ + export function umask(mask?: number): number; + + /** The object that is returned from a {@linkcode Deno.upgradeWebSocket} + * request. + * + * @category WebSockets */ + export interface WebSocketUpgrade { + /** The response object that represents the HTTP response to the client, + * which should be used to the {@linkcode RequestEvent} `.respondWith()` for + * the upgrade to be successful. */ + response: Response; + /** The {@linkcode WebSocket} interface to communicate to the client via a + * web socket. */ + socket: WebSocket; + } + + /** Options which can be set when performing a + * {@linkcode Deno.upgradeWebSocket} upgrade of a {@linkcode Request} + * + * @category WebSockets */ + export interface UpgradeWebSocketOptions { + /** Sets the `.protocol` property on the client side web socket to the + * value provided here, which should be one of the strings specified in the + * `protocols` parameter when requesting the web socket. This is intended + * for clients and servers to specify sub-protocols to use to communicate to + * each other. */ + protocol?: string; + /** If the client does not respond to this frame with a + * `pong` within the timeout specified, the connection is deemed + * unhealthy and is closed. The `close` and `error` event will be emitted. + * + * The unit is seconds, with a default of 30. + * Set to `0` to disable timeouts. */ + idleTimeout?: number; + } + + /** + * Upgrade an incoming HTTP request to a WebSocket. + * + * Given a {@linkcode Request}, returns a pair of {@linkcode WebSocket} and + * {@linkcode Response} instances. The original request must be responded to + * with the returned response for the websocket upgrade to be successful. + * + * ```ts + * Deno.serve((req) => { + * if (req.headers.get("upgrade") !== "websocket") { + * return new Response(null, { status: 501 }); + * } + * const { socket, response } = Deno.upgradeWebSocket(req); + * socket.addEventListener("open", () => { + * console.log("a client connected!"); + * }); + * socket.addEventListener("message", (event) => { + * if (event.data === "ping") { + * socket.send("pong"); + * } + * }); + * return response; + * }); + * ``` + * + * If the request body is disturbed (read from) before the upgrade is + * completed, upgrading fails. + * + * This operation does not yet consume the request or open the websocket. This + * only happens once the returned response has been passed to `respondWith()`. + * + * @category WebSockets + */ + export function upgradeWebSocket( + request: Request, + options?: UpgradeWebSocketOptions, + ): WebSocketUpgrade; + + /** Send a signal to process under given `pid`. The value and meaning of the + * `signal` to the process is operating system and process dependant. + * {@linkcode Signal} provides the most common signals. Default signal + * is `"SIGTERM"`. + * + * The term `kill` is adopted from the UNIX-like command line command `kill` + * which also signals processes. + * + * If `pid` is negative, the signal will be sent to the process group + * identified by `pid`. An error will be thrown if a negative `pid` is used on + * Windows. + * + * ```ts + * const command = new Deno.Command("sleep", { args: ["10000"] }); + * const child = command.spawn(); + * + * Deno.kill(child.pid, "SIGINT"); + * ``` + * + * Requires `allow-run` permission. + * + * @tags allow-run + * @category Subprocess + */ + export function kill(pid: number, signo?: Signal): void; + + /** The type of the resource record to resolve via DNS using + * {@linkcode Deno.resolveDns}. + * + * Only the listed types are supported currently. + * + * @category Network + */ + export type RecordType = + | "A" + | "AAAA" + | "ANAME" + | "CAA" + | "CNAME" + | "MX" + | "NAPTR" + | "NS" + | "PTR" + | "SOA" + | "SRV" + | "TXT"; + + /** + * Options which can be set when using {@linkcode Deno.resolveDns}. + * + * @category Network */ + export interface ResolveDnsOptions { + /** The name server to be used for lookups. + * + * If not specified, defaults to the system configuration. For example + * `/etc/resolv.conf` on Unix-like systems. */ + nameServer?: { + /** The IP address of the name server. */ + ipAddr: string; + /** The port number the query will be sent to. + * + * @default {53} */ + port?: number; + }; + /** + * An abort signal to allow cancellation of the DNS resolution operation. + * If the signal becomes aborted the resolveDns operation will be stopped + * and the promise returned will be rejected with an AbortError. + */ + signal?: AbortSignal; + } + + /** If {@linkcode Deno.resolveDns} is called with `"CAA"` record type + * specified, it will resolve with an array of objects with this interface. + * + * @category Network + */ + export interface CaaRecord { + /** If `true`, indicates that the corresponding property tag **must** be + * understood if the semantics of the CAA record are to be correctly + * interpreted by an issuer. + * + * Issuers **must not** issue certificates for a domain if the relevant CAA + * Resource Record set contains unknown property tags that have `critical` + * set. */ + critical: boolean; + /** An string that represents the identifier of the property represented by + * the record. */ + tag: string; + /** The value associated with the tag. */ + value: string; + } + + /** If {@linkcode Deno.resolveDns} is called with `"MX"` record type + * specified, it will return an array of objects with this interface. + * + * @category Network */ + export interface MxRecord { + /** A priority value, which is a relative value compared to the other + * preferences of MX records for the domain. */ + preference: number; + /** The server that mail should be delivered to. */ + exchange: string; + } + + /** If {@linkcode Deno.resolveDns} is called with `"NAPTR"` record type + * specified, it will return an array of objects with this interface. + * + * @category Network */ + export interface NaptrRecord { + order: number; + preference: number; + flags: string; + services: string; + regexp: string; + replacement: string; + } + + /** If {@linkcode Deno.resolveDns} is called with `"SOA"` record type + * specified, it will return an array of objects with this interface. + * + * @category Network */ + export interface SoaRecord { + mname: string; + rname: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minimum: number; + } + + /** If {@linkcode Deno.resolveDns} is called with `"SRV"` record type + * specified, it will return an array of objects with this interface. + * + * @category Network + */ + export interface SrvRecord { + priority: number; + weight: number; + port: number; + target: string; + } + + /** + * Performs DNS resolution against the given query, returning resolved + * records. + * + * Fails in the cases such as: + * + * - the query is in invalid format. + * - the options have an invalid parameter. For example `nameServer.port` is + * beyond the range of 16-bit unsigned integer. + * - the request timed out. + * + * ```ts + * const a = await Deno.resolveDns("example.com", "A"); + * + * const aaaa = await Deno.resolveDns("example.com", "AAAA", { + * nameServer: { ipAddr: "8.8.8.8", port: 53 }, + * }); + * ``` + * + * Requires `allow-net` permission. + * + * @tags allow-net + * @category Network + */ + export function resolveDns( + query: string, + recordType: "A" | "AAAA" | "ANAME" | "CNAME" | "NS" | "PTR", + options?: ResolveDnsOptions, + ): Promise; + + /** + * Performs DNS resolution against the given query, returning resolved + * records. + * + * Fails in the cases such as: + * + * - the query is in invalid format. + * - the options have an invalid parameter. For example `nameServer.port` is + * beyond the range of 16-bit unsigned integer. + * - the request timed out. + * + * ```ts + * const a = await Deno.resolveDns("example.com", "A"); + * + * const aaaa = await Deno.resolveDns("example.com", "AAAA", { + * nameServer: { ipAddr: "8.8.8.8", port: 53 }, + * }); + * ``` + * + * Requires `allow-net` permission. + * + * @tags allow-net + * @category Network + */ + export function resolveDns( + query: string, + recordType: "CAA", + options?: ResolveDnsOptions, + ): Promise; + + /** + * Performs DNS resolution against the given query, returning resolved + * records. + * + * Fails in the cases such as: + * + * - the query is in invalid format. + * - the options have an invalid parameter. For example `nameServer.port` is + * beyond the range of 16-bit unsigned integer. + * - the request timed out. + * + * ```ts + * const a = await Deno.resolveDns("example.com", "A"); + * + * const aaaa = await Deno.resolveDns("example.com", "AAAA", { + * nameServer: { ipAddr: "8.8.8.8", port: 53 }, + * }); + * ``` + * + * Requires `allow-net` permission. + * + * @tags allow-net + * @category Network + */ + export function resolveDns( + query: string, + recordType: "MX", + options?: ResolveDnsOptions, + ): Promise; + + /** + * Performs DNS resolution against the given query, returning resolved + * records. + * + * Fails in the cases such as: + * + * - the query is in invalid format. + * - the options have an invalid parameter. For example `nameServer.port` is + * beyond the range of 16-bit unsigned integer. + * - the request timed out. + * + * ```ts + * const a = await Deno.resolveDns("example.com", "A"); + * + * const aaaa = await Deno.resolveDns("example.com", "AAAA", { + * nameServer: { ipAddr: "8.8.8.8", port: 53 }, + * }); + * ``` + * + * Requires `allow-net` permission. + * + * @tags allow-net + * @category Network + */ + export function resolveDns( + query: string, + recordType: "NAPTR", + options?: ResolveDnsOptions, + ): Promise; + + /** + * Performs DNS resolution against the given query, returning resolved + * records. + * + * Fails in the cases such as: + * + * - the query is in invalid format. + * - the options have an invalid parameter. For example `nameServer.port` is + * beyond the range of 16-bit unsigned integer. + * - the request timed out. + * + * ```ts + * const a = await Deno.resolveDns("example.com", "A"); + * + * const aaaa = await Deno.resolveDns("example.com", "AAAA", { + * nameServer: { ipAddr: "8.8.8.8", port: 53 }, + * }); + * ``` + * + * Requires `allow-net` permission. + * + * @tags allow-net + * @category Network + */ + export function resolveDns( + query: string, + recordType: "SOA", + options?: ResolveDnsOptions, + ): Promise; + + /** + * Performs DNS resolution against the given query, returning resolved + * records. + * + * Fails in the cases such as: + * + * - the query is in invalid format. + * - the options have an invalid parameter. For example `nameServer.port` is + * beyond the range of 16-bit unsigned integer. + * - the request timed out. + * + * ```ts + * const a = await Deno.resolveDns("example.com", "A"); + * + * const aaaa = await Deno.resolveDns("example.com", "AAAA", { + * nameServer: { ipAddr: "8.8.8.8", port: 53 }, + * }); + * ``` + * + * Requires `allow-net` permission. + * + * @tags allow-net + * @category Network + */ + export function resolveDns( + query: string, + recordType: "SRV", + options?: ResolveDnsOptions, + ): Promise; + + /** + * Performs DNS resolution against the given query, returning resolved + * records. + * + * Fails in the cases such as: + * + * - the query is in invalid format. + * - the options have an invalid parameter. For example `nameServer.port` is + * beyond the range of 16-bit unsigned integer. + * - the request timed out. + * + * ```ts + * const a = await Deno.resolveDns("example.com", "A"); + * + * const aaaa = await Deno.resolveDns("example.com", "AAAA", { + * nameServer: { ipAddr: "8.8.8.8", port: 53 }, + * }); + * ``` + * + * Requires `allow-net` permission. + * + * @tags allow-net + * @category Network + */ + export function resolveDns( + query: string, + recordType: "TXT", + options?: ResolveDnsOptions, + ): Promise; + + /** + * Performs DNS resolution against the given query, returning resolved + * records. + * + * Fails in the cases such as: + * + * - the query is in invalid format. + * - the options have an invalid parameter. For example `nameServer.port` is + * beyond the range of 16-bit unsigned integer. + * - the request timed out. + * + * ```ts + * const a = await Deno.resolveDns("example.com", "A"); + * + * const aaaa = await Deno.resolveDns("example.com", "AAAA", { + * nameServer: { ipAddr: "8.8.8.8", port: 53 }, + * }); + * ``` + * + * Requires `allow-net` permission. + * + * @tags allow-net + * @category Network + */ + export function resolveDns( + query: string, + recordType: RecordType, + options?: ResolveDnsOptions, + ): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord[] + | SrvRecord[] + | string[][] + >; + + /** + * Make the timer of the given `id` block the event loop from finishing. + * + * @category Runtime + */ + export function refTimer(id: number): void; + + /** + * Make the timer of the given `id` not block the event loop from finishing. + * + * @category Runtime + */ + export function unrefTimer(id: number): void; + + /** + * Returns the user id of the process on POSIX platforms. Returns null on Windows. + * + * ```ts + * console.log(Deno.uid()); + * ``` + * + * Requires `allow-sys` permission. + * + * @tags allow-sys + * @category Runtime + */ + export function uid(): number | null; + + /** + * Returns the group id of the process on POSIX platforms. Returns null on windows. + * + * ```ts + * console.log(Deno.gid()); + * ``` + * + * Requires `allow-sys` permission. + * + * @tags allow-sys + * @category Runtime + */ + export function gid(): number | null; + + /** Additional information for an HTTP request and its connection. + * + * @category HTTP Server + */ + export interface ServeHandlerInfo { + /** The remote address of the connection. */ + remoteAddr: Addr; + /** The completion promise */ + completed: Promise; + } + + /** A handler for HTTP requests. Consumes a request and returns a response. + * + * If a handler throws, the server calling the handler will assume the impact + * of the error is isolated to the individual request. It will catch the error + * and if necessary will close the underlying connection. + * + * @category HTTP Server + */ + export type ServeHandler = ( + request: Request, + info: ServeHandlerInfo, + ) => Response | Promise; + + /** Interface that module run with `deno serve` subcommand must conform to. + * + * To ensure your code is type-checked properly, make sure to add `satisfies Deno.ServeDefaultExport` + * to the `export default { ... }` like so: + * + * ```ts + * export default { + * fetch(req) { + * return new Response("Hello world"); + * } + * } satisfies Deno.ServeDefaultExport; + * ``` + * + * @category HTTP Server + */ + export interface ServeDefaultExport { + /** A handler for HTTP requests. Consumes a request and returns a response. + * + * If a handler throws, the server calling the handler will assume the impact + * of the error is isolated to the individual request. It will catch the error + * and if necessary will close the underlying connection. + * + * @category HTTP Server + */ + fetch: ServeHandler; + } + + /** Options which can be set when calling {@linkcode Deno.serve}. + * + * @category HTTP Server + */ + export interface ServeOptions { + /** An {@linkcode AbortSignal} to close the server and all connections. */ + signal?: AbortSignal; + + /** The handler to invoke when route handlers throw an error. */ + onError?: (error: unknown) => Response | Promise; + + /** The callback which is called when the server starts listening. */ + onListen?: (localAddr: Addr) => void; + } + + /** + * Options that can be passed to `Deno.serve` to create a server listening on + * a TCP port. + * + * @category HTTP Server + */ + export interface ServeTcpOptions extends ServeOptions { + /** The transport to use. */ + transport?: "tcp"; + + /** The port to listen on. + * + * Set to `0` to listen on any available port. + * + * @default {8000} */ + port?: number; + + /** A literal IP address or host name that can be resolved to an IP address. + * + * __Note about `0.0.0.0`__ While listening `0.0.0.0` works on all platforms, + * the browsers on Windows don't work with the address `0.0.0.0`. + * You should show the message like `server running on localhost:8080` instead of + * `server running on 0.0.0.0:8080` if your program supports Windows. + * + * @default {"0.0.0.0"} */ + hostname?: string; + + /** Sets `SO_REUSEPORT` on POSIX systems. */ + reusePort?: boolean; + } + + /** + * Options that can be passed to `Deno.serve` to create a server listening on + * a Unix domain socket. + * + * @category HTTP Server + */ + export interface ServeUnixOptions extends ServeOptions { + /** The transport to use. */ + transport?: "unix"; + + /** The unix domain socket path to listen on. */ + path: string; + } + + /** + * @category HTTP Server + */ + export interface ServeInit { + /** The handler to invoke to process each incoming request. */ + handler: ServeHandler; + } + + /** An instance of the server created using `Deno.serve()` API. + * + * @category HTTP Server + */ + export interface HttpServer + extends AsyncDisposable { + /** A promise that resolves once server finishes - eg. when aborted using + * the signal passed to {@linkcode ServeOptions.signal}. + */ + finished: Promise; + + /** The local address this server is listening on. */ + addr: Addr; + + /** + * Make the server block the event loop from finishing. + * + * Note: the server blocks the event loop from finishing by default. + * This method is only meaningful after `.unref()` is called. + */ + ref(): void; + + /** Make the server not block the event loop from finishing. */ + unref(): void; + + /** Gracefully close the server. No more new connections will be accepted, + * while pending requests will be allowed to finish. + */ + shutdown(): Promise; + } + + /** Serves HTTP requests with the given handler. + * + * The below example serves with the port `8000` on hostname `"127.0.0.1"`. + * + * ```ts + * Deno.serve((_req) => new Response("Hello, world")); + * ``` + * + * @category HTTP Server + */ + export function serve( + handler: ServeHandler, + ): HttpServer; + /** Serves HTTP requests with the given option bag and handler. + * + * You can specify the socket path with `path` option. + * + * ```ts + * Deno.serve( + * { path: "path/to/socket" }, + * (_req) => new Response("Hello, world") + * ); + * ``` + * + * You can stop the server with an {@linkcode AbortSignal}. The abort signal + * needs to be passed as the `signal` option in the options bag. The server + * aborts when the abort signal is aborted. To wait for the server to close, + * await the promise returned from the `Deno.serve` API. + * + * ```ts + * const ac = new AbortController(); + * + * const server = Deno.serve( + * { signal: ac.signal, path: "path/to/socket" }, + * (_req) => new Response("Hello, world") + * ); + * server.finished.then(() => console.log("Server closed")); + * + * console.log("Closing server..."); + * ac.abort(); + * ``` + * + * By default `Deno.serve` prints the message + * `Listening on path/to/socket` on listening. If you like to + * change this behavior, you can specify a custom `onListen` callback. + * + * ```ts + * Deno.serve({ + * onListen({ path }) { + * console.log(`Server started at ${path}`); + * // ... more info specific to your server .. + * }, + * path: "path/to/socket", + * }, (_req) => new Response("Hello, world")); + * ``` + * + * @category HTTP Server + */ + export function serve( + options: ServeUnixOptions, + handler: ServeHandler, + ): HttpServer; + /** Serves HTTP requests with the given option bag and handler. + * + * You can specify an object with a port and hostname option, which is the + * address to listen on. The default is port `8000` on hostname `"0.0.0.0"`. + * + * You can change the address to listen on using the `hostname` and `port` + * options. The below example serves on port `3000` and hostname `"127.0.0.1"`. + * + * ```ts + * Deno.serve( + * { port: 3000, hostname: "127.0.0.1" }, + * (_req) => new Response("Hello, world") + * ); + * ``` + * + * You can stop the server with an {@linkcode AbortSignal}. The abort signal + * needs to be passed as the `signal` option in the options bag. The server + * aborts when the abort signal is aborted. To wait for the server to close, + * await the promise returned from the `Deno.serve` API. + * + * ```ts + * const ac = new AbortController(); + * + * const server = Deno.serve( + * { signal: ac.signal }, + * (_req) => new Response("Hello, world") + * ); + * server.finished.then(() => console.log("Server closed")); + * + * console.log("Closing server..."); + * ac.abort(); + * ``` + * + * By default `Deno.serve` prints the message + * `Listening on http://:/` on listening. If you like to + * change this behavior, you can specify a custom `onListen` callback. + * + * ```ts + * Deno.serve({ + * onListen({ port, hostname }) { + * console.log(`Server started at http://${hostname}:${port}`); + * // ... more info specific to your server .. + * }, + * }, (_req) => new Response("Hello, world")); + * ``` + * + * To enable TLS you must specify the `key` and `cert` options. + * + * ```ts + * const cert = "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n"; + * const key = "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"; + * Deno.serve({ cert, key }, (_req) => new Response("Hello, world")); + * ``` + * + * @category HTTP Server + */ + export function serve( + options: ServeTcpOptions | (ServeTcpOptions & TlsCertifiedKeyPem), + handler: ServeHandler, + ): HttpServer; + /** Serves HTTP requests with the given option bag. + * + * You can specify an object with the path option, which is the + * unix domain socket to listen on. + * + * ```ts + * const ac = new AbortController(); + * + * const server = Deno.serve({ + * path: "path/to/socket", + * handler: (_req) => new Response("Hello, world"), + * signal: ac.signal, + * onListen({ path }) { + * console.log(`Server started at ${path}`); + * }, + * }); + * server.finished.then(() => console.log("Server closed")); + * + * console.log("Closing server..."); + * ac.abort(); + * ``` + * + * @category HTTP Server + */ + export function serve( + options: ServeUnixOptions & ServeInit, + ): HttpServer; + /** Serves HTTP requests with the given option bag. + * + * You can specify an object with a port and hostname option, which is the + * address to listen on. The default is port `8000` on hostname `"0.0.0.0"`. + * + * ```ts + * const ac = new AbortController(); + * + * const server = Deno.serve({ + * port: 3000, + * hostname: "127.0.0.1", + * handler: (_req) => new Response("Hello, world"), + * signal: ac.signal, + * onListen({ port, hostname }) { + * console.log(`Server started at http://${hostname}:${port}`); + * }, + * }); + * server.finished.then(() => console.log("Server closed")); + * + * console.log("Closing server..."); + * ac.abort(); + * ``` + * + * @category HTTP Server + */ + export function serve( + options: + & (ServeTcpOptions | (ServeTcpOptions & TlsCertifiedKeyPem)) + & ServeInit, + ): HttpServer; + + /** All plain number types for interfacing with foreign functions. + * + * @category FFI + */ + export type NativeNumberType = + | "u8" + | "i8" + | "u16" + | "i16" + | "u32" + | "i32" + | "f32" + | "f64"; + + /** All BigInt number types for interfacing with foreign functions. + * + * @category FFI + */ + export type NativeBigIntType = "u64" | "i64" | "usize" | "isize"; + + /** The native boolean type for interfacing to foreign functions. + * + * @category FFI + */ + export type NativeBooleanType = "bool"; + + /** The native pointer type for interfacing to foreign functions. + * + * @category FFI + */ + export type NativePointerType = "pointer"; + + /** The native buffer type for interfacing to foreign functions. + * + * @category FFI + */ + export type NativeBufferType = "buffer"; + + /** The native function type for interfacing with foreign functions. + * + * @category FFI + */ + export type NativeFunctionType = "function"; + + /** The native void type for interfacing with foreign functions. + * + * @category FFI + */ + export type NativeVoidType = "void"; + + /** The native struct type for interfacing with foreign functions. + * + * @category FFI + */ + export interface NativeStructType { + readonly struct: readonly NativeType[]; + } + + /** + * @category FFI + */ + export const brand: unique symbol; + + /** + * @category FFI + */ + export type NativeU8Enum = "u8" & { [brand]: T }; + /** + * @category FFI + */ + export type NativeI8Enum = "i8" & { [brand]: T }; + /** + * @category FFI + */ + export type NativeU16Enum = "u16" & { [brand]: T }; + /** + * @category FFI + */ + export type NativeI16Enum = "i16" & { [brand]: T }; + /** + * @category FFI + */ + export type NativeU32Enum = "u32" & { [brand]: T }; + /** + * @category FFI + */ + export type NativeI32Enum = "i32" & { [brand]: T }; + /** + * @category FFI + */ + export type NativeTypedPointer = "pointer" & { + [brand]: T; + }; + /** + * @category FFI + */ + export type NativeTypedFunction = + & "function" + & { + [brand]: T; + }; + + /** All supported types for interfacing with foreign functions. + * + * @category FFI + */ + export type NativeType = + | NativeNumberType + | NativeBigIntType + | NativeBooleanType + | NativePointerType + | NativeBufferType + | NativeFunctionType + | NativeStructType; + + /** @category FFI + */ + export type NativeResultType = NativeType | NativeVoidType; + + /** Type conversion for foreign symbol parameters and unsafe callback return + * types. + * + * @category FFI + */ + export type ToNativeType = T extends + NativeStructType ? BufferSource + : T extends NativeNumberType ? T extends NativeU8Enum ? U + : T extends NativeI8Enum ? U + : T extends NativeU16Enum ? U + : T extends NativeI16Enum ? U + : T extends NativeU32Enum ? U + : T extends NativeI32Enum ? U + : number + : T extends NativeBigIntType ? bigint + : T extends NativeBooleanType ? boolean + : T extends NativePointerType + ? T extends NativeTypedPointer ? U | null + : PointerValue + : T extends NativeFunctionType + ? T extends NativeTypedFunction ? PointerValue | null + : PointerValue + : T extends NativeBufferType ? BufferSource | null + : never; + + /** Type conversion for unsafe callback return types. + * + * @category FFI + */ + export type ToNativeResultType< + T extends NativeResultType = NativeResultType, + > = T extends NativeStructType ? BufferSource + : T extends NativeNumberType ? T extends NativeU8Enum ? U + : T extends NativeI8Enum ? U + : T extends NativeU16Enum ? U + : T extends NativeI16Enum ? U + : T extends NativeU32Enum ? U + : T extends NativeI32Enum ? U + : number + : T extends NativeBigIntType ? bigint + : T extends NativeBooleanType ? boolean + : T extends NativePointerType + ? T extends NativeTypedPointer ? U | null + : PointerValue + : T extends NativeFunctionType + ? T extends NativeTypedFunction ? PointerObject | null + : PointerValue + : T extends NativeBufferType ? BufferSource | null + : T extends NativeVoidType ? void + : never; + + /** A utility type for conversion of parameter types of foreign functions. + * + * @category FFI + */ + export type ToNativeParameterTypes = + // + [T[number][]] extends [T] ? ToNativeType[] + : [readonly T[number][]] extends [T] ? readonly ToNativeType[] + : T extends readonly [...NativeType[]] ? { + [K in keyof T]: ToNativeType; + } + : never; + + /** Type conversion for foreign symbol return types and unsafe callback + * parameters. + * + * @category FFI + */ + export type FromNativeType = T extends + NativeStructType ? Uint8Array + : T extends NativeNumberType ? T extends NativeU8Enum ? U + : T extends NativeI8Enum ? U + : T extends NativeU16Enum ? U + : T extends NativeI16Enum ? U + : T extends NativeU32Enum ? U + : T extends NativeI32Enum ? U + : number + : T extends NativeBigIntType ? bigint + : T extends NativeBooleanType ? boolean + : T extends NativePointerType + ? T extends NativeTypedPointer ? U | null + : PointerValue + : T extends NativeBufferType ? PointerValue + : T extends NativeFunctionType + ? T extends NativeTypedFunction ? PointerObject | null + : PointerValue + : never; + + /** Type conversion for foreign symbol return types. + * + * @category FFI + */ + export type FromNativeResultType< + T extends NativeResultType = NativeResultType, + > = T extends NativeStructType ? Uint8Array + : T extends NativeNumberType ? T extends NativeU8Enum ? U + : T extends NativeI8Enum ? U + : T extends NativeU16Enum ? U + : T extends NativeI16Enum ? U + : T extends NativeU32Enum ? U + : T extends NativeI32Enum ? U + : number + : T extends NativeBigIntType ? bigint + : T extends NativeBooleanType ? boolean + : T extends NativePointerType + ? T extends NativeTypedPointer ? U | null + : PointerValue + : T extends NativeBufferType ? PointerValue + : T extends NativeFunctionType + ? T extends NativeTypedFunction ? PointerObject | null + : PointerValue + : T extends NativeVoidType ? void + : never; + + /** @category FFI + */ + export type FromNativeParameterTypes = + // + [T[number][]] extends [T] ? FromNativeType[] + : [readonly T[number][]] extends [T] + ? readonly FromNativeType[] + : T extends readonly [...NativeType[]] ? { + [K in keyof T]: FromNativeType; + } + : never; + + /** The interface for a foreign function as defined by its parameter and result + * types. + * + * @category FFI + */ + export interface ForeignFunction< + Parameters extends readonly NativeType[] = readonly NativeType[], + Result extends NativeResultType = NativeResultType, + NonBlocking extends boolean = boolean, + > { + /** Name of the symbol. + * + * Defaults to the key name in symbols object. */ + name?: string; + /** The parameters of the foreign function. */ + parameters: Parameters; + /** The result (return value) of the foreign function. */ + result: Result; + /** When `true`, function calls will run on a dedicated blocking thread and + * will return a `Promise` resolving to the `result`. */ + nonblocking?: NonBlocking; + /** When `true`, dlopen will not fail if the symbol is not found. + * Instead, the symbol will be set to `null`. + * + * @default {false} */ + optional?: boolean; + } + + /** @category FFI + */ + export interface ForeignStatic { + /** Name of the symbol, defaults to the key name in symbols object. */ + name?: string; + /** The type of the foreign static value. */ + type: Type; + /** When `true`, dlopen will not fail if the symbol is not found. + * Instead, the symbol will be set to `null`. + * + * @default {false} */ + optional?: boolean; + } + + /** A foreign library interface descriptor. + * + * @category FFI + */ + export interface ForeignLibraryInterface { + [name: string]: ForeignFunction | ForeignStatic; + } + + /** A utility type that infers a foreign symbol. + * + * @category FFI + */ + export type StaticForeignSymbol = + T extends ForeignFunction ? FromForeignFunction + : T extends ForeignStatic ? FromNativeType + : never; + + /** @category FFI + */ + export type FromForeignFunction = + T["parameters"] extends readonly [] ? () => StaticForeignSymbolReturnType + : ( + ...args: ToNativeParameterTypes + ) => StaticForeignSymbolReturnType; + + /** @category FFI + */ + export type StaticForeignSymbolReturnType = + ConditionalAsync>; + + /** @category FFI + */ + export type ConditionalAsync< + IsAsync extends boolean | undefined, + T, + > = IsAsync extends true ? Promise : T; + + /** A utility type that infers a foreign library interface. + * + * @category FFI + */ + export type StaticForeignLibraryInterface = + { + [K in keyof T]: T[K]["optional"] extends true + ? StaticForeignSymbol | null + : StaticForeignSymbol; + }; + + /** A non-null pointer, represented as an object + * at runtime. The object's prototype is `null` + * and cannot be changed. The object cannot be + * assigned to either and is thus entirely read-only. + * + * To interact with memory through a pointer use the + * {@linkcode UnsafePointerView} class. To create a + * pointer from an address or the get the address of + * a pointer use the static methods of the + * {@linkcode UnsafePointer} class. + * + * @category FFI + */ + export interface PointerObject { + [brand]: T; + } + + /** Pointers are represented either with a {@linkcode PointerObject} + * object or a `null` if the pointer is null. + * + * @category FFI + */ + export type PointerValue = null | PointerObject; + + /** A collection of static functions for interacting with pointer objects. + * + * @category FFI + */ + export class UnsafePointer { + /** Create a pointer from a numeric value. This one is really dangerous! */ + static create(value: bigint): PointerValue; + /** Returns `true` if the two pointers point to the same address. */ + static equals(a: PointerValue, b: PointerValue): boolean; + /** Return the direct memory pointer to the typed array in memory. */ + static of( + value: Deno.UnsafeCallback | BufferSource, + ): PointerValue; + /** Return a new pointer offset from the original by `offset` bytes. */ + static offset( + value: PointerObject, + offset: number, + ): PointerValue; + /** Get the numeric value of a pointer */ + static value(value: PointerValue): bigint; + } + + /** An unsafe pointer view to a memory location as specified by the `pointer` + * value. The `UnsafePointerView` API follows the standard built in interface + * {@linkcode DataView} for accessing the underlying types at an memory + * location (numbers, strings and raw bytes). + * + * @category FFI + */ + export class UnsafePointerView { + constructor(pointer: PointerObject); + + pointer: PointerObject; + + /** Gets a boolean at the specified byte offset from the pointer. */ + getBool(offset?: number): boolean; + /** Gets an unsigned 8-bit integer at the specified byte offset from the + * pointer. */ + getUint8(offset?: number): number; + /** Gets a signed 8-bit integer at the specified byte offset from the + * pointer. */ + getInt8(offset?: number): number; + /** Gets an unsigned 16-bit integer at the specified byte offset from the + * pointer. */ + getUint16(offset?: number): number; + /** Gets a signed 16-bit integer at the specified byte offset from the + * pointer. */ + getInt16(offset?: number): number; + /** Gets an unsigned 32-bit integer at the specified byte offset from the + * pointer. */ + getUint32(offset?: number): number; + /** Gets a signed 32-bit integer at the specified byte offset from the + * pointer. */ + getInt32(offset?: number): number; + /** Gets an unsigned 64-bit integer at the specified byte offset from the + * pointer. */ + getBigUint64(offset?: number): bigint; + /** Gets a signed 64-bit integer at the specified byte offset from the + * pointer. */ + getBigInt64(offset?: number): bigint; + /** Gets a signed 32-bit float at the specified byte offset from the + * pointer. */ + getFloat32(offset?: number): number; + /** Gets a signed 64-bit float at the specified byte offset from the + * pointer. */ + getFloat64(offset?: number): number; + /** Gets a pointer at the specified byte offset from the pointer */ + getPointer(offset?: number): PointerValue; + /** Gets a C string (`null` terminated string) at the specified byte offset + * from the pointer. */ + getCString(offset?: number): string; + /** Gets a C string (`null` terminated string) at the specified byte offset + * from the specified pointer. */ + static getCString(pointer: PointerObject, offset?: number): string; + /** Gets an `ArrayBuffer` of length `byteLength` at the specified byte + * offset from the pointer. */ + getArrayBuffer(byteLength: number, offset?: number): ArrayBuffer; + /** Gets an `ArrayBuffer` of length `byteLength` at the specified byte + * offset from the specified pointer. */ + static getArrayBuffer( + pointer: PointerObject, + byteLength: number, + offset?: number, + ): ArrayBuffer; + /** Copies the memory of the pointer into a typed array. + * + * Length is determined from the typed array's `byteLength`. + * + * Also takes optional byte offset from the pointer. */ + copyInto(destination: BufferSource, offset?: number): void; + /** Copies the memory of the specified pointer into a typed array. + * + * Length is determined from the typed array's `byteLength`. + * + * Also takes optional byte offset from the pointer. */ + static copyInto( + pointer: PointerObject, + destination: BufferSource, + offset?: number, + ): void; + } + + /** An unsafe pointer to a function, for calling functions that are not present + * as symbols. + * + * @category FFI + */ + export class UnsafeFnPointer { + /** The pointer to the function. */ + pointer: PointerObject; + /** The definition of the function. */ + definition: Fn; + + constructor( + pointer: PointerObject>>, + definition: Fn, + ); + + /** Call the foreign function. */ + call: FromForeignFunction; + } + + /** Definition of a unsafe callback function. + * + * @category FFI + */ + export interface UnsafeCallbackDefinition< + Parameters extends readonly NativeType[] = readonly NativeType[], + Result extends NativeResultType = NativeResultType, + > { + /** The parameters of the callbacks. */ + parameters: Parameters; + /** The current result of the callback. */ + result: Result; + } + + /** An unsafe callback function. + * + * @category FFI + */ + export type UnsafeCallbackFunction< + Parameters extends readonly NativeType[] = readonly NativeType[], + Result extends NativeResultType = NativeResultType, + > = Parameters extends readonly [] ? () => ToNativeResultType + : ( + ...args: FromNativeParameterTypes + ) => ToNativeResultType; + + /** An unsafe function pointer for passing JavaScript functions as C function + * pointers to foreign function calls. + * + * The function pointer remains valid until the `close()` method is called. + * + * All `UnsafeCallback` are always thread safe in that they can be called from + * foreign threads without crashing. However, they do not wake up the Deno event + * loop by default. + * + * If a callback is to be called from foreign threads, use the `threadSafe()` + * static constructor or explicitly call `ref()` to have the callback wake up + * the Deno event loop when called from foreign threads. This also stops + * Deno's process from exiting while the callback still exists and is not + * unref'ed. + * + * Use `deref()` to then allow Deno's process to exit. Calling `deref()` on + * a ref'ed callback does not stop it from waking up the Deno event loop when + * called from foreign threads. + * + * @category FFI + */ + export class UnsafeCallback< + const Definition extends UnsafeCallbackDefinition = + UnsafeCallbackDefinition, + > { + constructor( + definition: Definition, + callback: UnsafeCallbackFunction< + Definition["parameters"], + Definition["result"] + >, + ); + + /** The pointer to the unsafe callback. */ + readonly pointer: PointerObject; + /** The definition of the unsafe callback. */ + readonly definition: Definition; + /** The callback function. */ + readonly callback: UnsafeCallbackFunction< + Definition["parameters"], + Definition["result"] + >; + + /** + * Creates an {@linkcode UnsafeCallback} and calls `ref()` once to allow it to + * wake up the Deno event loop when called from foreign threads. + * + * This also stops Deno's process from exiting while the callback still + * exists and is not unref'ed. + */ + static threadSafe< + Definition extends UnsafeCallbackDefinition = UnsafeCallbackDefinition, + >( + definition: Definition, + callback: UnsafeCallbackFunction< + Definition["parameters"], + Definition["result"] + >, + ): UnsafeCallback; + + /** + * Increments the callback's reference counting and returns the new + * reference count. + * + * After `ref()` has been called, the callback always wakes up the + * Deno event loop when called from foreign threads. + * + * If the callback's reference count is non-zero, it keeps Deno's + * process from exiting. + */ + ref(): number; + + /** + * Decrements the callback's reference counting and returns the new + * reference count. + * + * Calling `unref()` does not stop a callback from waking up the Deno + * event loop when called from foreign threads. + * + * If the callback's reference counter is zero, it no longer keeps + * Deno's process from exiting. + */ + unref(): number; + + /** + * Removes the C function pointer associated with this instance. + * + * Continuing to use the instance or the C function pointer after closing + * the `UnsafeCallback` will lead to errors and crashes. + * + * Calling this method sets the callback's reference counting to zero, + * stops the callback from waking up the Deno event loop when called from + * foreign threads and no longer keeps Deno's process from exiting. + */ + close(): void; + } + + /** A dynamic library resource. Use {@linkcode Deno.dlopen} to load a dynamic + * library and return this interface. + * + * @category FFI + */ + export interface DynamicLibrary { + /** All of the registered library along with functions for calling them. */ + symbols: StaticForeignLibraryInterface; + /** Removes the pointers associated with the library symbols. + * + * Continuing to use symbols that are part of the library will lead to + * errors and crashes. + * + * Calling this method will also immediately set any references to zero and + * will no longer keep Deno's process from exiting. + */ + close(): void; + } + + /** Opens an external dynamic library and registers symbols, making foreign + * functions available to be called. + * + * Requires `allow-ffi` permission. Loading foreign dynamic libraries can in + * theory bypass all of the sandbox permissions. While it is a separate + * permission users should acknowledge in practice that is effectively the + * same as running with the `allow-all` permission. + * + * @example Given a C library which exports a foreign function named `add()` + * + * ```ts + * // Determine library extension based on + * // your OS. + * let libSuffix = ""; + * switch (Deno.build.os) { + * case "windows": + * libSuffix = "dll"; + * break; + * case "darwin": + * libSuffix = "dylib"; + * break; + * default: + * libSuffix = "so"; + * break; + * } + * + * const libName = `./libadd.${libSuffix}`; + * // Open library and define exported symbols + * const dylib = Deno.dlopen( + * libName, + * { + * "add": { parameters: ["isize", "isize"], result: "isize" }, + * } as const, + * ); + * + * // Call the symbol `add` + * const result = dylib.symbols.add(35n, 34n); // 69n + * + * console.log(`Result from external addition of 35 and 34: ${result}`); + * ``` + * + * @tags allow-ffi + * @category FFI + */ + export function dlopen( + filename: string | URL, + symbols: S, + ): DynamicLibrary; + + /** + * A custom `HttpClient` for use with {@linkcode fetch} function. This is + * designed to allow custom certificates or proxies to be used with `fetch()`. + * + * @example ```ts + * const caCert = await Deno.readTextFile("./ca.pem"); + * const client = Deno.createHttpClient({ caCerts: [ caCert ] }); + * const req = await fetch("https://myserver.com", { client }); + * ``` + * + * @category Fetch + */ + export class HttpClient implements Disposable { + /** Close the HTTP client. */ + close(): void; + + [Symbol.dispose](): void; + } + + /** + * The options used when creating a {@linkcode Deno.HttpClient}. + * + * @category Fetch + */ + export interface CreateHttpClientOptions { + /** A list of root certificates that will be used in addition to the + * default root certificates to verify the peer's certificate. + * + * Must be in PEM format. */ + caCerts?: string[]; + /** A HTTP proxy to use for new connections. */ + proxy?: Proxy; + /** Sets the maximum number of idle connections per host allowed in the pool. */ + poolMaxIdlePerHost?: number; + /** Set an optional timeout for idle sockets being kept-alive. + * Set to false to disable the timeout. */ + poolIdleTimeout?: number | false; + /** + * Whether HTTP/1.1 is allowed or not. + * + * @default {true} + */ + http1?: boolean; + /** Whether HTTP/2 is allowed or not. + * + * @default {true} + */ + http2?: boolean; + /** Whether setting the host header is allowed or not. + * + * @default {false} + */ + allowHost?: boolean; + } + + /** + * The definition of a proxy when specifying + * {@linkcode Deno.CreateHttpClientOptions}. + * + * @category Fetch + */ + export interface Proxy { + /** The string URL of the proxy server to use. */ + url: string; + /** The basic auth credentials to be used against the proxy server. */ + basicAuth?: BasicAuth; + } + + /** + * Basic authentication credentials to be used with a {@linkcode Deno.Proxy} + * server when specifying {@linkcode Deno.CreateHttpClientOptions}. + * + * @category Fetch + */ + export interface BasicAuth { + /** The username to be used against the proxy server. */ + username: string; + /** The password to be used against the proxy server. */ + password: string; + } + + /** Create a custom HttpClient to use with {@linkcode fetch}. This is an + * extension of the web platform Fetch API which allows Deno to use custom + * TLS CA certificates and connect via a proxy while using `fetch()`. + * + * The `cert` and `key` options can be used to specify a client certificate + * and key to use when connecting to a server that requires client + * authentication (mutual TLS or mTLS). The `cert` and `key` options must be + * provided in PEM format. + * + * @example ```ts + * const caCert = await Deno.readTextFile("./ca.pem"); + * const client = Deno.createHttpClient({ caCerts: [ caCert ] }); + * const response = await fetch("https://myserver.com", { client }); + * ``` + * + * @example ```ts + * const client = Deno.createHttpClient({ + * proxy: { url: "http://myproxy.com:8080" } + * }); + * const response = await fetch("https://myserver.com", { client }); + * ``` + * + * @example ```ts + * const key = "----BEGIN PRIVATE KEY----..."; + * const cert = "----BEGIN CERTIFICATE----..."; + * const client = Deno.createHttpClient({ key, cert }); + * const response = await fetch("https://myserver.com", { client }); + * ``` + * + * @category Fetch + */ + export function createHttpClient( + options: + | CreateHttpClientOptions + | (CreateHttpClientOptions & TlsCertifiedKeyPem), + ): HttpClient; + + export {}; // only export exports +} + +// Copyright 2018-2025 the Deno authors. MIT license. + +// deno-lint-ignore-file no-explicit-any + +/// +/// + +/** + * The Console interface provides methods for logging information to the console, + * as well as other utility methods for debugging and inspecting code. + * Methods include logging, debugging, and timing functionality. + * @see https://developer.mozilla.org/en-US/docs/Web/API/console + * + * @category I/O + */ + +interface Console { + /** + * Tests that an expression is true. If not, logs an error message + * @param condition The expression to test for truthiness + * @param data Additional arguments to be printed if the assertion fails + * @example + * ```ts + * console.assert(1 === 1, "This won't show"); + * console.assert(1 === 2, "This will show an error"); + * ``` + */ + assert(condition?: boolean, ...data: any[]): void; + + /** + * Clears the console if the environment allows it + * @example + * ```ts + * console.clear(); + * ``` + */ + clear(): void; + + /** + * Maintains an internal counter for a given label, incrementing it each time the method is called + * @param label The label to count. Defaults to 'default' + * @example + * ```ts + * console.count('myCounter'); + * console.count('myCounter'); // Will show: myCounter: 2 + * ``` + */ + count(label?: string): void; + + /** + * Resets the counter for a given label + * @param label The label to reset. Defaults to 'default' + * @example + * ```ts + * console.count('myCounter'); + * console.countReset('myCounter'); // Resets to 0 + * ``` + */ + countReset(label?: string): void; + + /** + * Outputs a debugging message to the console + * @param data Values to be printed to the console + * @example + * ```ts + * console.debug('Debug message', { detail: 'some data' }); + * ``` + */ + debug(...data: any[]): void; + + /** + * Displays a list of the properties of a specified object + * @param item Object to display + * @param options Formatting options + * @example + * ```ts + * console.dir({ name: 'object', value: 42 }, { depth: 1 }); + * ``` + */ + dir(item?: any, options?: any): void; + + /** + * @ignore + */ + dirxml(...data: any[]): void; + + /** + * Outputs an error message to the console. + * This method routes the output to stderr, + * unlike other console methods that route to stdout. + * @param data Values to be printed to the console + * @example + * ```ts + * console.error('Error occurred:', new Error('Something went wrong')); + * ``` + */ + error(...data: any[]): void; + + /** + * Creates a new inline group in the console, indenting subsequent console messages + * @param data Labels for the group + * @example + * ```ts + * console.group('Group 1'); + * console.log('Inside group 1'); + * console.groupEnd(); + * ``` + */ + group(...data: any[]): void; + + /** + * Creates a new inline group in the console that is initially collapsed + * @param data Labels for the group + * @example + * ```ts + * console.groupCollapsed('Details'); + * console.log('Hidden until expanded'); + * console.groupEnd(); + * ``` + */ + groupCollapsed(...data: any[]): void; + + /** + * Exits the current inline group in the console + * @example + * ```ts + * console.group('Group'); + * console.log('Grouped message'); + * console.groupEnd(); + * ``` + */ + groupEnd(): void; + + /** + * Outputs an informational message to the console + * @param data Values to be printed to the console + * @example + * ```ts + * console.info('Application started', { version: '1.0.0' }); + * ``` + */ + info(...data: any[]): void; + + /** + * Outputs a message to the console + * @param data Values to be printed to the console + * @example + * ```ts + * console.log('Hello', 'World', 123); + * ``` + */ + log(...data: any[]): void; + + /** + * Displays tabular data as a table + * @param tabularData Data to be displayed in table format + * @param properties Array of property names to be displayed + * @example + * ```ts + * console.table([ + * { name: 'John', age: 30 }, + * { name: 'Jane', age: 25 } + * ]); + * ``` + */ + table(tabularData?: any, properties?: string[]): void; + + /** + * Starts a timer you can use to track how long an operation takes + * @param label Timer label. Defaults to 'default' + * @example + * ```ts + * console.time('operation'); + * // ... some code + * console.timeEnd('operation'); + * ``` + */ + time(label?: string): void; + + /** + * Stops a timer that was previously started + * @param label Timer label to stop. Defaults to 'default' + * @example + * ```ts + * console.time('operation'); + * // ... some code + * console.timeEnd('operation'); // Prints: operation: 1234ms + * ``` + */ + timeEnd(label?: string): void; + + /** + * Logs the current value of a timer that was previously started + * @param label Timer label + * @param data Additional data to log + * @example + * ```ts + * console.time('process'); + * // ... some code + * console.timeLog('process', 'Checkpoint A'); + * ``` + */ + timeLog(label?: string, ...data: any[]): void; + + /** + * Outputs a stack trace to the console + * @param data Values to be printed to the console + * @example + * ```ts + * console.trace('Trace message'); + * ``` + */ + trace(...data: any[]): void; + + /** + * Outputs a warning message to the console + * @param data Values to be printed to the console + * @example + * ```ts + * console.warn('Deprecated feature used'); + * ``` + */ + warn(...data: any[]): void; + + /** + * Adds a marker to the DevTools Performance panel + * @param label Label for the timestamp + * @example + * ```ts + * console.timeStamp('Navigation Start'); + * ``` + */ + timeStamp(label?: string): void; + + /** + * Starts recording a performance profile + * @param label Profile label + * @example + * ```ts + * console.profile('Performance Profile'); + * // ... code to profile + * console.profileEnd('Performance Profile'); + * ``` + */ + profile(label?: string): void; + + /** + * Stops recording a performance profile + * @param label Profile label to stop + * @example + * ```ts + * console.profile('Performance Profile'); + * // ... code to profile + * console.profileEnd('Performance Profile'); + * ``` + */ + profileEnd(label?: string): void; +} + +// Copyright 2018-2025 the Deno authors. MIT license. + +// deno-lint-ignore-file no-explicit-any no-var + +/// +/// + +/** + * Iterator for the URLSearchParams class, used to iterate over key-value pairs in search parameters. + * + * @example + * ```ts + * const url = new URL('https://example.org/path?a=1&b=2'); + * const queryString = url.search.substring(1); // Remove the leading '?' + * const params = new URLSearchParams(queryString); + * const iterator = params.entries(); + * console.log(iterator.next().value); // ['a', '1'] + * console.log(iterator.next().value); // ['b', '2'] + * ``` + * + * @category URL + */ +interface URLSearchParamsIterator + extends IteratorObject { + [Symbol.iterator](): URLSearchParamsIterator; +} + +/** + * URLSearchParams provides methods for working with the query string of a URL. + * + * Use this interface to: + * - Parse query parameters from URLs + * - Build and modify query strings + * - Handle form data (when used with FormData) + * - Safely encode/decode URL parameter values + * + * @category URL + */ +interface URLSearchParams { + /** Appends a specified key/value pair as a new search parameter. + * + * ```ts + * let searchParams = new URLSearchParams(); + * searchParams.append('name', 'first'); + * searchParams.append('name', 'second'); + * ``` + */ + append(name: string, value: string): void; + + /** Deletes search parameters that match a name, and optional value, + * from the list of all search parameters. + * + * ```ts + * let searchParams = new URLSearchParams([['name', 'value']]); + * searchParams.delete('name'); + * searchParams.delete('name', 'value'); + * ``` + */ + delete(name: string, value?: string): void; + + /** Returns all the values associated with a given search parameter + * as an array. + * + * ```ts + * searchParams.getAll('name'); + * ``` + */ + getAll(name: string): string[]; + + /** Returns the first value associated to the given search parameter. + * + * ```ts + * searchParams.get('name'); + * ``` + */ + get(name: string): string | null; + + /** Returns a boolean value indicating if a given parameter, + * or parameter and value pair, exists. + * + * ```ts + * searchParams.has('name'); + * searchParams.has('name', 'value'); + * ``` + */ + has(name: string, value?: string): boolean; + + /** Sets the value associated with a given search parameter to the + * given value. If there were several matching values, this method + * deletes the others. If the search parameter doesn't exist, this + * method creates it. + * + * ```ts + * searchParams.set('name', 'value'); + * ``` + */ + set(name: string, value: string): void; + + /** Sort all key/value pairs contained in this object in place and + * return undefined. The sort order is according to Unicode code + * points of the keys. + * + * ```ts + * searchParams.sort(); + * ``` + */ + sort(): void; + + /** Calls a function for each element contained in this object in + * place and return undefined. Optionally accepts an object to use + * as this when executing callback as second argument. + * + * ```ts + * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); + * params.forEach((value, key, parent) => { + * console.log(value, key, parent); + * }); + * ``` + */ + forEach( + callbackfn: (value: string, key: string, parent: this) => void, + thisArg?: any, + ): void; + + /** Returns an iterator allowing to go through all keys contained + * in this object. + * + * ```ts + * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); + * for (const key of params.keys()) { + * console.log(key); + * } + * ``` + */ + keys(): URLSearchParamsIterator; + + /** Returns an iterator allowing to go through all values contained + * in this object. + * + * ```ts + * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); + * for (const value of params.values()) { + * console.log(value); + * } + * ``` + */ + values(): URLSearchParamsIterator; + + /** Returns an iterator allowing to go through all key/value + * pairs contained in this object. + * + * ```ts + * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); + * for (const [key, value] of params.entries()) { + * console.log(key, value); + * } + * ``` + */ + entries(): URLSearchParamsIterator<[string, string]>; + + /** Returns an iterator allowing to go through all key/value + * pairs contained in this object. + * + * ```ts + * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); + * for (const [key, value] of params) { + * console.log(key, value); + * } + * ``` + */ + [Symbol.iterator](): URLSearchParamsIterator<[string, string]>; + + /** Returns a query string suitable for use in a URL. + * + * ```ts + * searchParams.toString(); + * ``` + */ + toString(): string; + + /** Contains the number of search parameters + * + * ```ts + * searchParams.size + * ``` + */ + readonly size: number; +} + +/** @category URL */ +declare var URLSearchParams: { + readonly prototype: URLSearchParams; + /** + * Creates a new URLSearchParams object for parsing query strings. + * + * URLSearchParams is Deno's built-in query string parser, providing a standard + * way to parse, manipulate, and stringify URL query parameters. Instead of manually + * parsing query strings with regex or string operations, use this API for robust + * handling of URL query parameters. + * + * @example + * ```ts + * // From a URL object's query string (recommended approach for parsing query strings in URLs) + * const url = new URL('https://example.org/path?foo=bar&baz=qux'); + * const params = url.searchParams; // No need to manually extract the query string + * console.log(params.get('foo')); // Logs "bar" + * + * // Manually parsing a query string from a URL + * const urlString = 'https://example.org/path?foo=bar&baz=qux'; + * const queryString = urlString.split('?')[1]; // Extract query string part + * const params2 = new URLSearchParams(queryString); + * console.log(params2.get('foo')); // Logs "bar" + * + * // Empty search parameters + * const params3 = new URLSearchParams(); + * console.log(params3.toString()); // Logs "" + * + * // From a string + * const params4 = new URLSearchParams("foo=bar&baz=qux"); + * console.log(params4.get("foo")); // Logs "bar" + * + * // From an array of pairs + * const params5 = new URLSearchParams([["foo", "1"], ["bar", "2"]]); + * console.log(params5.toString()); // Logs "foo=1&bar=2" + * + * // From a record object + * const params6 = new URLSearchParams({"foo": "1", "bar": "2"}); + * console.log(params6.toString()); // Logs "foo=1&bar=2" + * ``` + */ + new ( + init?: + | Iterable + | Record + | string + | URLSearchParams, + ): URLSearchParams; +}; + +/** The URL interface represents an object providing static methods used for + * creating, parsing, and manipulating URLs in Deno. + * + * Use the URL API for safely parsing, constructing, normalizing, and encoding URLs. + * This is the preferred way to work with URLs in Deno rather than manual string + * manipulation which can lead to errors and security issues. + * + * @see https://developer.mozilla.org/docs/Web/API/URL + * + * @category URL + */ +interface URL { + /** + * The hash property of the URL interface is a string that starts with a `#` and is followed by the fragment identifier of the URL. + * It returns an empty string if the URL does not contain a fragment identifier. + * + * @example + * ```ts + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); // Logs "#bar" + * + * const myOtherURL = new URL('https://example.org'); + * console.log(myOtherURL.hash); // Logs "" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/hash + */ + hash: string; + + /** + * The `host` property of the URL interface is a string that includes the {@linkcode URL.hostname} and the {@linkcode URL.port} if one is specified in the URL includes by including a `:` followed by the port number. + * + * @example + * ```ts + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.host); // Logs "example.org" + * + * const myOtherURL = new URL('https://example.org:8080/foo'); + * console.log(myOtherURL.host); // Logs "example.org:8080" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/host + */ + host: string; + + /** + * The `hostname` property of the URL interface is a string that represents the fully qualified domain name of the URL. + * + * @example + * ```ts + * const myURL = new URL('https://foo.example.org/bar'); + * console.log(myURL.hostname); // Logs "foo.example.org" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/hostname + */ + hostname: string; + + /** + * The `href` property of the URL interface is a string that represents the complete URL. + * + * @example + * ```ts + * const myURL = new URL('https://foo.example.org/bar?baz=qux#quux'); + * console.log(myURL.href); // Logs "https://foo.example.org/bar?baz=qux#quux" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/href + */ + href: string; + + /** + * The `toString()` method of the URL interface returns a string containing the complete URL. + * + * @example + * ```ts + * const myURL = new URL('https://foo.example.org/bar'); + * console.log(myURL.toString()); // Logs "https://foo.example.org/bar" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/toString + */ + toString(): string; + + /** + * The `origin` property of the URL interface is a string that represents the origin of the URL, that is the {@linkcode URL.protocol}, {@linkcode URL.host}, and {@linkcode URL.port}. + * + * @example + * ```ts + * const myURL = new URL('https://foo.example.org/bar'); + * console.log(myURL.origin); // Logs "https://foo.example.org" + * + * const myOtherURL = new URL('https://example.org:8080/foo'); + * console.log(myOtherURL.origin); // Logs "https://example.org:8080" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/origin + */ + readonly origin: string; + + /** + * The `password` property of the URL interface is a string that represents the password specified in the URL. + * + * @example + * ```ts + * const myURL = new URL('https://someone:somepassword@example.org/baz'); + * console.log(myURL.password); // Logs "somepassword" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/password + */ + password: string; + + /** + * The `pathname` property of the URL interface is a string that represents the path of the URL. + * + * @example + * ```ts + * const myURL = new URL('https://example.org/foo/bar'); + * console.log(myURL.pathname); // Logs "/foo/bar" + * + * const myOtherURL = new URL('https://example.org'); + * console.log(myOtherURL.pathname); // Logs "/" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/pathname + */ + pathname: string; + + /** + * The `port` property of the URL interface is a string that represents the port of the URL if an explicit port has been specified in the URL. + * + * @example + * ```ts + * const myURL = new URL('https://example.org:8080/foo'); + * console.log(myURL.port); // Logs "8080" + * + * const myOtherURL = new URL('https://example.org/foo'); + * console.log(myOtherURL.port); // Logs "" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/port + */ + port: string; + + /** + * The `protocol` property of the URL interface is a string that represents the protocol scheme of the URL and includes a trailing `:`. + * + * @example + * ```ts + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.protocol); // Logs "https:" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/protocol + */ + protocol: string; + + /** + * The `search` property of the URL interface is a string that represents the search string, or the query string, of the URL. + * This includes the `?` character and the but excludes identifiers within the represented resource such as the {@linkcode URL.hash}. More granular control can be found using {@linkcode URL.searchParams} property. + * + * @example + * ```ts + * const myURL = new URL('https://example.org/foo?bar=baz'); + * console.log(myURL.search); // Logs "?bar=baz" + * + * const myOtherURL = new URL('https://example.org/foo?bar=baz#quux'); + * console.log(myOtherURL.search); // Logs "?bar=baz" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/search + */ + search: string; + + /** + * The `searchParams` property of the URL interface provides a direct interface to + * query parameters through a {@linkcode URLSearchParams} object. + * + * This property offers a convenient way to: + * - Parse URL query parameters + * - Manipulate query strings + * - Add, modify, or delete URL parameters + * - Work with form data in a URL-encoded format + * - Handle query string encoding/decoding automatically + * + * @example + * ```ts + * // Parse and access query parameters from a URL + * const myURL = new URL('https://example.org/search?term=deno&page=2&sort=desc'); + * const params = myURL.searchParams; + * + * console.log(params.get('term')); // Logs "deno" + * console.log(params.get('page')); // Logs "2" + * + * // Check if a parameter exists + * console.log(params.has('sort')); // Logs true + * + * // Add or modify parameters (automatically updates the URL) + * params.append('filter', 'recent'); + * params.set('page', '3'); + * console.log(myURL.href); // URL is updated with new parameters + * + * // Remove a parameter + * params.delete('sort'); + * + * // Iterate over all parameters + * for (const [key, value] of params) { + * console.log(`${key}: ${value}`); + * } + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/searchParams + */ + readonly searchParams: URLSearchParams; + + /** + * The `username` property of the URL interface is a string that represents the username of the URL. + * + * @example + * ```ts + * const myURL = new URL('https://someone:somepassword@example.org/baz'); + * console.log(myURL.username); // Logs "someone" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/username + */ + username: string; + + /** + * The `toJSON()` method of the URL interface returns a JSON representation of the URL. + * + * @example + * ```ts + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.toJSON()); // Logs "https://example.org/foo" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/toJSON + */ + toJSON(): string; +} + +/** The URL interface represents an object providing static methods used for + * creating, parsing, and manipulating URLs. + * + * @see https://developer.mozilla.org/docs/Web/API/URL + * + * @category URL + */ +declare var URL: { + readonly prototype: URL; + /** + * Creates a new URL object by parsing the specified URL string with an optional base URL. + * Throws a TypeError If the URL is invalid or if a relative URL is provided without a base. + * + * Use this to parse and validate URLs safely. Use this instead of string + * manipulation to ensure correct URL handling, proper encoding, and protection against + * security issues like path traversal attacks. + * + * @example + * ```ts + * // Creating a URL from an absolute URL string + * const url1 = new URL('https://example.org/foo'); + * console.log(url1.href); // Logs "https://example.org/foo" + * + * // Creating a URL from a relative URL string with a base URL + * const url2 = new URL('/bar', 'https://example.org'); + * console.log(url2.href); // Logs "https://example.org/bar" + * + * // Joining path segments safely (prevents path traversal) + * const baseUrl = 'https://api.example.com/v1'; + * const userInput = '../secrets'; // Potentially malicious input + * const safeUrl = new URL(userInput, baseUrl); + * console.log(safeUrl.href); // Correctly resolves to "https://api.example.com/secrets" + * + * // Constructing URLs with proper encoding + * const search = 'query with spaces'; + * const url3 = new URL('https://example.org/search'); + * url3.searchParams.set('q', search); // Automatically handles URL encoding + * console.log(url3.href); // "https://example.org/search?q=query+with+spaces" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/URL + */ + new (url: string | URL, base?: string | URL): URL; + + /** + * Parses a URL string or URL object and returns a URL object. + * + * @example + * ```ts + * const myURL = URL.parse('https://example.org'); + * console.log(myURL.href); // Logs "https://example.org/" + * console.log(myURL.hostname); // Logs "example.org" + * console.log(myURL.pathname); // Logs "/" + * console.log(myURL.protocol); // Logs "https:" + * + * const baseURL = new URL('https://example.org'); + * const myNewURL = URL.parse('/foo', baseURL); + * console.log(myNewURL.href); // Logs "https://example.org/foo" + * console.log(myNewURL.hostname); // Logs "example.org" + * console.log(myNewURL.pathname); // Logs "/foo" + * console.log(myNewURL.protocol); // Logs "https:" + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/parse_static + */ + parse(url: string | URL, base?: string | URL): URL | null; + + /** + * Returns a boolean value indicating if a URL string is valid and can be parsed. + * + * @example + * ```ts + * // Check if an absolute URL string is valid + * console.log(URL.canParse('https://example.org')); // Logs true + * console.log(URL.canParse('https:://example.org')); // Logs false + * + * // Check if a relative URL string with a base is valid + * console.log(URL.canParse('/foo', 'https://example.org')); // Logs true + * console.log(URL.canParse('/foo', 'https:://example.org')); // Logs false + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/canParse_static + */ + canParse(url: string | URL, base?: string | URL): boolean; + + /** + * Creates a unique, temporary URL that represents a given Blob, File, or MediaSource object. + * + * This method is particularly useful for: + * - Creating URLs for dynamically generated content + * - Working with blobs in a browser context + * - Creating workers from dynamically generated code + * - Setting up temporary URL references for file downloads + * + * Note: Always call URL.revokeObjectURL() when you're done using the URL to prevent memory leaks. + * + * @example + * ```ts + * // Create a URL string for a Blob + * const blob = new Blob(["Hello, world!"], { type: "text/plain" }); + * const url = URL.createObjectURL(blob); + * console.log(url); // Logs something like "blob:null/1234-5678-9101-1121" + * + * // Dynamic web worker creation in Deno + * const workerCode = ` + * self.onmessage = (e) => { + * self.postMessage(e.data.toUpperCase()); + * }; + * `; + * const workerBlob = new Blob([workerCode], { type: "application/javascript" }); + * const workerUrl = URL.createObjectURL(workerBlob); + * const worker = new Worker(workerUrl, { type: "module" }); + * + * worker.onmessage = (e) => console.log(e.data); + * worker.postMessage("hello from deno"); + * + * // Always revoke when done to prevent memory leaks + * URL.revokeObjectURL(workerUrl); + * ``` + * + * @see https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static + */ + createObjectURL(blob: Blob): string; + + /** + * Revokes a previously created object URL, freeing the memory associated with it. + * + * Important for memory management in applications that create dynamic URLs. + * Once an object URL is revoked: + * - It can no longer be used to fetch the content it referenced + * - The browser/runtime is allowed to release the memory or resources associated with it + * - Workers created via the URL will continue to run, but the URL becomes invalid for new creations + * + * For security and performance in Deno applications, always revoke object URLs as soon as + * they're no longer needed, especially when processing large files or generating many URLs. + * + * @see https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static + */ + revokeObjectURL(url: string): void; +}; + +/** @category URL */ +interface URLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} + +/** @category URL */ +type URLPatternInput = string | URLPatternInit; + +/** @category URL */ +interface URLPatternComponentResult { + input: string; + groups: Record; +} + +/** `URLPatternResult` is the object returned from `URLPattern.exec`. + * + * @category URL + */ +interface URLPatternResult { + /** The inputs provided when matching. */ + inputs: [URLPatternInit] | [URLPatternInit, string]; + + /** The matched result for the `protocol` matcher. */ + protocol: URLPatternComponentResult; + /** The matched result for the `username` matcher. */ + username: URLPatternComponentResult; + /** The matched result for the `password` matcher. */ + password: URLPatternComponentResult; + /** The matched result for the `hostname` matcher. */ + hostname: URLPatternComponentResult; + /** The matched result for the `port` matcher. */ + port: URLPatternComponentResult; + /** The matched result for the `pathname` matcher. */ + pathname: URLPatternComponentResult; + /** The matched result for the `search` matcher. */ + search: URLPatternComponentResult; + /** The matched result for the `hash` matcher. */ + hash: URLPatternComponentResult; +} + +/** + * Options for the {@linkcode URLPattern} constructor. + * + * @category URL + */ +interface URLPatternOptions { + /** + * Enables case-insensitive matching. + * + * @default {false} + */ + ignoreCase: boolean; +} + +/** + * The URLPattern API provides a web platform primitive for matching URLs based + * on a convenient pattern syntax. + * + * Common use cases for URLPattern include: + * - Building routers for web applications + * - Pattern-matching URLs for middleware + * - Extracting parameters from URL paths + * - URL-based feature toggles + * - Routing in serverless and edge functions + * + * The syntax is based on path-to-regexp, supporting wildcards, named capture groups, + * regular groups, and group modifiers - similar to Express.js route patterns. + * + * @example + * ```ts + * // Basic routing with URLPattern (similar to Express.js) + * const routes = [ + * new URLPattern({ pathname: "/users" }), + * new URLPattern({ pathname: "/users/:id" }), + * new URLPattern({ pathname: "/products/:category/:id?" }), + * ]; + * + * // Check incoming request against routes + * function handleRequest(req: Request) { + * const url = new URL(req.url); + * + * for (const route of routes) { + * const match = route.exec(url); + * if (match) { + * // Extract parameters from the URL + * const params = match.pathname.groups; + * return new Response(`Matched: ${JSON.stringify(params)}`); + * } + * } + * + * return new Response("Not found", { status: 404 }); + * } + * ``` + * + * @example + * ```ts + * // Matching different URL parts + * const apiPattern = new URLPattern({ + * protocol: "https", + * hostname: "api.example.com", + * pathname: "/v:version/:resource/:id?", + * search: "*", // Match any query string + * }); + * + * const match = apiPattern.exec("https://api.example.com/v1/users/123?format=json"); + * if (match) { + * console.log(match.pathname.groups.version); // "1" + * console.log(match.pathname.groups.resource); // "users" + * console.log(match.pathname.groups.id); // "123" + * } + * ``` + * + * @category URL + */ +interface URLPattern { + /** + * Test if the given input matches the stored pattern. + * + * The input can either be provided as an absolute URL string with an optional base, + * relative URL string with a required base, or as individual components + * in the form of an `URLPatternInit` object. + * + * ```ts + * const pattern = new URLPattern("https://example.com/books/:id"); + * + * // Test an absolute url string. + * console.log(pattern.test("https://example.com/books/123")); // true + * + * // Test a relative url with a base. + * console.log(pattern.test("/books/123", "https://example.com")); // true + * + * // Test an object of url components. + * console.log(pattern.test({ pathname: "/books/123" })); // true + * ``` + */ + test(input: URLPatternInput, baseURL?: string): boolean; + + /** + * Match the given input against the stored pattern. + * + * The input can either be provided as an absolute URL string with an optional base, + * relative URL string with a required base, or as individual components + * in the form of an `URLPatternInit` object. + * + * ```ts + * const pattern = new URLPattern("https://example.com/books/:id"); + * + * // Match an absolute url string. + * let match = pattern.exec("https://example.com/books/123"); + * console.log(match.pathname.groups.id); // 123 + * + * // Match a relative url with a base. + * match = pattern.exec("/books/123", "https://example.com"); + * console.log(match.pathname.groups.id); // 123 + * + * // Match an object of url components. + * match = pattern.exec({ pathname: "/books/123" }); + * console.log(match.pathname.groups.id); // 123 + * ``` + */ + exec(input: URLPatternInput, baseURL?: string): URLPatternResult | null; + + /** The pattern string for the `protocol`. */ + readonly protocol: string; + /** The pattern string for the `username`. */ + readonly username: string; + /** The pattern string for the `password`. */ + readonly password: string; + /** The pattern string for the `hostname`. */ + readonly hostname: string; + /** The pattern string for the `port`. */ + readonly port: string; + /** The pattern string for the `pathname`. */ + readonly pathname: string; + /** The pattern string for the `search`. */ + readonly search: string; + /** The pattern string for the `hash`. */ + readonly hash: string; + + /** Whether or not any of the specified groups use regexp groups. */ + readonly hasRegExpGroups: boolean; +} + +/** + * The URLPattern API provides a web platform primitive for matching URLs based + * on a convenient pattern syntax. + * + * The syntax is based on path-to-regexp. Wildcards, named capture groups, + * regular groups, and group modifiers are all supported. + * + * ```ts + * // Specify the pattern as structured data. + * const pattern = new URLPattern({ pathname: "/users/:user" }); + * const match = pattern.exec("https://blog.example.com/users/joe"); + * console.log(match.pathname.groups.user); // joe + * ``` + * + * ```ts + * // Specify a fully qualified string pattern. + * const pattern = new URLPattern("https://example.com/books/:id"); + * console.log(pattern.test("https://example.com/books/123")); // true + * console.log(pattern.test("https://deno.land/books/123")); // false + * ``` + * + * ```ts + * // Specify a relative string pattern with a base URL. + * const pattern = new URLPattern("/article/:id", "https://blog.example.com"); + * console.log(pattern.test("https://blog.example.com/article")); // false + * console.log(pattern.test("https://blog.example.com/article/123")); // true + * ``` + * + * @category URL + */ +declare var URLPattern: { + readonly prototype: URLPattern; + new ( + input: URLPatternInput, + baseURL: string, + options?: URLPatternOptions, + ): URLPattern; + new (input?: URLPatternInput, options?: URLPatternOptions): URLPattern; +}; + +// Copyright 2018-2025 the Deno authors. MIT license. + +// deno-lint-ignore-file no-explicit-any no-var + +/// +/// + +/** @category Platform */ +interface DOMException extends Error { + readonly name: string; + readonly message: string; + /** @deprecated */ + readonly code: number; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; +} + +/** @category Platform */ +declare var DOMException: { + readonly prototype: DOMException; + new (message?: string, name?: string): DOMException; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; +}; + +/** @category Events */ +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +/** An event which takes place in the DOM. + * + * @category Events + */ +interface Event { + /** Returns true or false depending on how event was initialized. True if + * event goes through its target's ancestors in reverse tree order, and + * false otherwise. */ + readonly bubbles: boolean; + /** @deprecated */ + cancelBubble: boolean; + /** Returns true or false depending on how event was initialized. Its return + * value does not always carry meaning, but true can indicate that part of the + * operation during which event was dispatched, can be canceled by invoking + * the preventDefault() method. */ + readonly cancelable: boolean; + /** Returns true or false depending on how event was initialized. True if + * event invokes listeners past a ShadowRoot node that is the root of its + * target, and false otherwise. */ + readonly composed: boolean; + /** Returns the object whose event listener's callback is currently being + * invoked. */ + readonly currentTarget: EventTarget | null; + /** Returns true if preventDefault() was invoked successfully to indicate + * cancellation, and false otherwise. */ + readonly defaultPrevented: boolean; + /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE, + * AT_TARGET, and BUBBLING_PHASE. */ + readonly eventPhase: number; + /** Returns true if event was dispatched by the user agent, and false + * otherwise. */ + readonly isTrusted: boolean; + /** @deprecated */ + returnValue: boolean; + /** @deprecated */ + readonly srcElement: EventTarget | null; + /** Returns the object to which event is dispatched (its target). */ + readonly target: EventTarget | null; + /** Returns the event's timestamp as the number of milliseconds measured + * relative to the time origin. */ + readonly timeStamp: number; + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + /** Returns the invocation target objects of event's path (objects on which + * listeners will be invoked), except for any nodes in shadow trees of which + * the shadow root's mode is "closed" that are not reachable from event's + * currentTarget. */ + composedPath(): EventTarget[]; + /** @deprecated */ + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + /** If invoked when the cancelable attribute value is true, and while + * executing a listener for the event with passive set to false, signals to + * the operation that caused event to be dispatched that it needs to be + * canceled. */ + preventDefault(): void; + /** Invoking this method prevents event from reaching any registered event + * listeners after the current one finishes running and, when dispatched in a + * tree, also prevents event from reaching any other objects. */ + stopImmediatePropagation(): void; + /** When dispatched in a tree, invoking this method prevents event from + * reaching any objects other than the current object. */ + stopPropagation(): void; + readonly NONE: 0; + readonly CAPTURING_PHASE: 1; + readonly AT_TARGET: 2; + readonly BUBBLING_PHASE: 3; +} + +/** An event which takes place in the DOM. + * + * @category Events + */ +declare var Event: { + readonly prototype: Event; + new (type: string, eventInitDict?: EventInit): Event; + readonly NONE: 0; + readonly CAPTURING_PHASE: 1; + readonly AT_TARGET: 2; + readonly BUBBLING_PHASE: 3; +}; + +/** + * EventTarget is a DOM interface implemented by objects that can receive events + * and may have listeners for them. + * + * @category Events + */ +interface EventTarget { + /** Appends an event listener for events whose type attribute value is type. + * The callback argument sets the callback that will be invoked when the event + * is dispatched. + * + * The options argument sets listener-specific options. For compatibility this + * can be a boolean, in which case the method behaves exactly as if the value + * was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked + * when the event's eventPhase attribute value is BUBBLING_PHASE. When false + * (or not present), callback will not be invoked when event's eventPhase + * attribute value is CAPTURING_PHASE. Either way, callback will be invoked if + * event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not + * cancel the event by invoking preventDefault(). This is used to enable + * performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be + * invoked once after which the event listener will be removed. + * + * The event listener is appended to target's event listener list and is not + * appended if it has the same type, callback, and capture. */ + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | AddEventListenerOptions, + ): void; + /** Dispatches a synthetic event to event target and returns true if either + * event's cancelable attribute value is false or its preventDefault() method + * was not invoked, and false otherwise. */ + dispatchEvent(event: Event): boolean; + /** Removes the event listener in target's event listener list with the same + * type, callback, and options. */ + removeEventListener( + type: string, + callback: EventListenerOrEventListenerObject | null, + options?: EventListenerOptions | boolean, + ): void; +} + +/** + * EventTarget is a DOM interface implemented by objects that can receive events + * and may have listeners for them. + * + * @category Events + */ +declare var EventTarget: { + readonly prototype: EventTarget; + new (): EventTarget; +}; + +/** @category Events */ +interface EventListener { + (evt: Event): void; +} + +/** @category Events */ +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +/** @category Events */ +type EventListenerOrEventListenerObject = + | EventListener + | EventListenerObject; + +/** @category Events */ +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; + signal?: AbortSignal; +} + +/** @category Events */ +interface EventListenerOptions { + capture?: boolean; +} + +/** @category Events */ +interface ProgressEventInit extends EventInit { + lengthComputable?: boolean; + loaded?: number; + total?: number; +} + +/** Events measuring progress of an underlying process, like an HTTP request + * (for an XMLHttpRequest, or the loading of the underlying resource of an + * ,