or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

array-operations.mdfunction-utilities.mdindex.mdmath-operations.mdobject-operations.mdpromise-utilities.mdstring-operations.mdtime-performance.mdtype-guards.md
tile.json

tessl/npm-antfu--utils

Opinionated collection of common JavaScript / TypeScript utils by @antfu

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@antfu/utils@9.2.x

To install, run

npx @tessl/cli install tessl/npm-antfu--utils@9.2.0

index.mddocs/

@antfu/utils

@antfu/utils is a comprehensive TypeScript utility library providing an opinionated collection of common JavaScript/TypeScript utilities. The library is designed for modern development workflows with tree-shakable ESM modules, full TypeScript support, and extensive type utilities.

Package Information

  • Package Name: @antfu/utils
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @antfu/utils (as devDependency)

Core Imports

import { toArray, isObject, sleep, clamp } from "@antfu/utils";

For CommonJS:

const { toArray, isObject, sleep, clamp } = require("@antfu/utils");

Import specific type utilities:

import type { Arrayable, Nullable, Awaitable } from "@antfu/utils";

Basic Usage

import { toArray, partition, deepMerge, sleep, template } from "@antfu/utils";

// Convert single values or arrays to arrays
const items = toArray("hello"); // ["hello"]
const moreItems = toArray(["a", "b"]); // ["a", "b"]

// Partition arrays by conditions
const [odds, evens] = partition([1, 2, 3, 4, 5], n => n % 2 === 1);
// odds: [1, 3, 5], evens: [2, 4]

// Deep merge objects
const merged = deepMerge({ a: 1 }, { b: 2, c: { d: 3 } });
// { a: 1, b: 2, c: { d: 3 } }

// Async utilities
await sleep(1000); // Wait 1 second

// Template strings
const result = template("Hello {name}!", { name: "World" });
// "Hello World!"

Architecture

@antfu/utils is organized into focused modules:

  • Functional Design: Pure functions with predictable behavior and no side effects
  • Type Safety: Full TypeScript integration with comprehensive type definitions
  • Tree Shaking: ESM modules designed for optimal bundling with unused code elimination
  • Category Organization: Functions grouped by domain (array, object, string, etc.)
  • Utility Types: Advanced TypeScript types for common patterns (Arrayable<T>, Nullable<T>)

Capabilities

Array Operations

Comprehensive array manipulation utilities including conversion, partitioning, filtering, and transformation operations.

function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
function partition<T>(array: readonly T[], ...filters: PartitionFilter<T>[]): T[][];
function uniq<T>(array: readonly T[]): T[];
function last<T>(array: readonly T[]): T | undefined;
function shuffle<T>(array: T[]): T[];

Array Operations

Object Operations

Object manipulation and transformation utilities with type-safe operations and deep merging capabilities.

function deepMerge<T, S>(target: T, ...sources: S[]): DeepMerge<T, S>;
function objectMap<K, V, NK, NV>(obj: Record<K, V>, fn: (key: K, value: V) => [NK, NV] | undefined): Record<NK, NV>;
function objectPick<O, T>(obj: O, keys: T[], omitUndefined?: boolean): Pick<O, T>;
function isKeyOf<T>(obj: T, k: keyof any): k is keyof T;

Object Operations

Type Guards & Validation

Type checking utilities and type guards for runtime validation and type narrowing, plus core utility functions.

function isObject(val: any): val is object;
function isString(val: unknown): val is string;
function isNumber(val: any): val is number;
function notNullish<T>(v: T | null | undefined): v is NonNullable<T>;
function isTruthy<T>(v: T): v is NonNullable<T>;
function assert(condition: boolean, message: string): asserts condition;
function getTypeName(v: any): string;
function noop(): void;

Type Guards & Validation

String Operations

String manipulation utilities including templating, formatting, and transformation functions.

function template(str: string, object: Record<string | number, any>, fallback?: string | ((key: string) => string)): string;
function ensurePrefix(prefix: string, str: string): string;
function ensureSuffix(suffix: string, str: string): string;
function capitalize(str: string): string;
function randomStr(size?: number, dict?: string): string;

String Operations

Promise & Async Utilities

Advanced promise management utilities including singleton promises, promise locks, and utility classes for managing multiple promises.

function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;
function sleep(ms: number, callback?: Fn<any>): Promise<void>;
function createPromiseLock(): PromiseLock;
function p<T>(items?: Iterable<T>, options?: POptions): PInstance<T>;

Promise & Async Utilities

Math Operations

Mathematical utility functions including clamping, interpolation, and arithmetic operations.

function clamp(n: number, min: number, max: number): number;
function sum(...args: number[] | number[][]): number;
function lerp(min: number, max: number, t: number): number;
function remap(n: number, inMin: number, inMax: number, outMin: number, outMax: number): number;

Math Operations

Function Utilities

Function manipulation and execution utilities including batching, tapping, and control flow helpers.

function batchInvoke(functions: Nullable<Fn>[]): void;
function invoke<T>(fn: () => T): T;
function tap<T>(value: T, callback: (value: T) => void): T;
function throttle<T extends (...args: any[]) => any>(delay: number, callback: T, options?: object): ReturnWithCancel<T>;
function debounce<T extends (...args: any[]) => any>(delay: number, callback: T, options?: object): ReturnWithCancel<T>;

Function Utilities

Time & Performance

Time-related utilities and performance helpers for timestamps and timing operations.

function timestamp(): number;

Time & Performance

Core Types

Essential TypeScript type utilities used throughout the library:

// Core utility types
type Arrayable<T> = T | Array<T>;
type Nullable<T> = T | null | undefined;
type Awaitable<T> = T | PromiseLike<T>;
type Fn<T = void> = () => T;
type Constructor<T = void> = new (...args: any[]) => T;
type ElementOf<T> = T extends (infer E)[] ? E : never;

// Advanced type utilities
type DeepMerge<F, S> = MergeInsertions<{
  [K in keyof F | keyof S]: K extends keyof S & keyof F
    ? DeepMerge<F[K], S[K]>
    : K extends keyof S
      ? S[K]
      : K extends keyof F
        ? F[K]
        : never;
}>;

type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
type ArgumentsType<T> = T extends ((...args: infer A) => any) ? A : never;