CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sindresorhus--is

Type check values with comprehensive TypeScript type guards and runtime assertions

Pending
Overview
Eval results
Files

collections.mddocs/

Collections and Emptiness

Specialized checks for empty and non-empty collections including arrays, objects, strings, maps, and sets. These methods help validate collection states and ensure non-empty collections for safe operations.

Capabilities

Array Emptiness Checking

Check if arrays are empty or contain items.

/**
 * Check if value is an empty array
 * @param value - Value to check
 * @returns True if value is empty array
 */
function isEmptyArray(value: unknown): value is never[];

/**
 * Check if value is a non-empty array
 * @param value - Value to check
 * @returns True if value is non-empty array
 */
function isNonEmptyArray<T = unknown, Item = unknown>(value: T | Item[]): value is [Item, ...Item[]];

Usage Examples:

import is from '@sindresorhus/is';

is.emptyArray([]); // => true
is.emptyArray([1, 2, 3]); // => false
is.emptyArray('not array'); // => false

is.nonEmptyArray([1, 2, 3]); // => true
is.nonEmptyArray([]); // => false

// Type guard usage
function processArray(arr: unknown) {
  if (is.nonEmptyArray(arr)) {
    // arr is now typed as [unknown, ...unknown[]]
    console.log('First item:', arr[0]);
    console.log('Length:', arr.length); // guaranteed > 0
  }
}

Object Emptiness Checking

Check if objects have enumerable properties.

/**
 * Check if value is an empty object (no enumerable properties)
 * @param value - Value to check
 * @returns True if value is empty object
 */
function isEmptyObject<Key extends keyof any = string>(value: unknown): value is Record<Key, never>;

/**
 * Check if value is a non-empty object (has enumerable properties)
 * @param value - Value to check
 * @returns True if value is non-empty object
 */
function isNonEmptyObject<Key extends keyof any = string, Value = unknown>(value: unknown): value is Record<Key, Value>;

Usage Examples:

import is from '@sindresorhus/is';

is.emptyObject({}); // => true
is.emptyObject({a: 1}); // => false
is.emptyObject([]); // => false (arrays are not plain objects)
is.emptyObject(new Map()); // => false (Maps are not plain objects)

is.nonEmptyObject({a: 1}); // => true
is.nonEmptyObject({}); // => false

// Note: Only checks enumerable properties
const obj = {};
Object.defineProperty(obj, 'hidden', {
  value: 42,
  enumerable: false
});
is.emptyObject(obj); // => true (hidden property is not enumerable)

Map Emptiness Checking

Check if Map objects are empty or contain entries.

/**
 * Check if value is an empty Map
 * @param value - Value to check
 * @returns True if value is empty Map
 */
function isEmptyMap(value: unknown): value is Map<never, never>;

/**
 * Check if value is a non-empty Map
 * @param value - Value to check
 * @returns True if value is non-empty Map
 */
function isNonEmptyMap<Key = unknown, Value = unknown>(value: unknown): value is Map<Key, Value>;

Usage Examples:

import is from '@sindresorhus/is';

const emptyMap = new Map();
const mapWithItems = new Map([['key', 'value']]);

is.emptyMap(emptyMap); // => true
is.emptyMap(mapWithItems); // => false
is.emptyMap({}); // => false

is.nonEmptyMap(mapWithItems); // => true
is.nonEmptyMap(emptyMap); // => false

// Type guard usage
function processMap(map: unknown) {
  if (is.nonEmptyMap(map)) {
    // map is now typed as Map<unknown, unknown> with size > 0
    console.log('Map size:', map.size);
    for (const [key, value] of map) {
      console.log(key, value);
    }
  }
}

Set Emptiness Checking

Check if Set objects are empty or contain values.

/**
 * Check if value is an empty Set
 * @param value - Value to check
 * @returns True if value is empty Set
 */
function isEmptySet(value: unknown): value is Set<never>;

/**
 * Check if value is a non-empty Set
 * @param value - Value to check
 * @returns True if value is non-empty Set
 */
function isNonEmptySet<T = unknown>(value: unknown): value is Set<T>;

Usage Examples:

import is from '@sindresorhus/is';

const emptySet = new Set();
const setWithItems = new Set([1, 2, 3]);

is.emptySet(emptySet); // => true
is.emptySet(setWithItems); // => false
is.emptySet([]); // => false

is.nonEmptySet(setWithItems); // => true
is.nonEmptySet(emptySet); // => false

// Type guard usage
function processSet(set: unknown) {
  if (is.nonEmptySet(set)) {
    // set is now typed as Set<unknown> with size > 0
    console.log('Set size:', set.size);
    for (const value of set) {
      console.log(value);
    }
  }
}

Array-like Type Checking

Check if a value is array-like (has a length property and indexed access).

/**
 * Check if value is array-like (has length property)
 * @param value - Value to check
 * @returns True if value is array-like
 */
function isArrayLike<T = unknown>(value: unknown): value is ArrayLike<T>;

type ArrayLike<T> = {
  readonly [index: number]: T;
  readonly length: number;
};

Usage Examples:

import is from '@sindresorhus/is';

is.arrayLike([]); // => true
is.arrayLike('hello'); // => true (strings are array-like)
is.arrayLike({0: 'a', 1: 'b', length: 2}); // => true
is.arrayLike(document.querySelectorAll('div')); // => true (NodeList)

function processArguments() {
  is.arrayLike(arguments); // => true
}

is.arrayLike({}); // => false
is.arrayLike(() => {}); // => false

Tuple-like Type Checking

Check if a value matches a tuple structure with type guards.

/**
 * Check if value matches tuple structure with guards
 * @param value - Value to check
 * @param guards - Array of type guard functions
 * @returns True if value matches tuple structure
 */
function isTupleLike<T extends Array<TypeGuard<unknown>>>(
  value: unknown, 
  guards: [...T]
): value is ResolveTypesOfTypeGuardsTuple<T>;

type TypeGuard<T> = (value: unknown) => value is T;

Usage Examples:

import is from '@sindresorhus/is';

// Check for [string, number] tuple
const guards = [is.string, is.number] as const;
is.tupleLike(['hello', 42], guards); // => true
is.tupleLike(['hello', 'world'], guards); // => false
is.tupleLike(['hello'], guards); // => false (wrong length)

// Type guard usage
function processTuple(value: unknown) {
  if (is.tupleLike(value, [is.string, is.number, is.boolean])) {
    // value is now typed as [string, number, boolean]
    const [str, num, bool] = value;
    console.log(str.toUpperCase(), num * 2, !bool);
  }
}

// More complex example
const complexGuards = [
  is.string,
  (v: unknown): v is {id: number} => is.plainObject(v) && is.number((v as any).id)
] as const;

if (is.tupleLike(someValue, complexGuards)) {
  // someValue is typed as [string, {id: number}]
  console.log(someValue[0].length, someValue[1].id);
}

Valid Length Checking

Check if a value is a valid length (safe integer >= 0).

/**
 * Check if value is a valid length (safe integer >= 0)
 * @param value - Value to check
 * @returns True if value is valid length
 */
function isValidLength(value: unknown): value is number;

Usage Examples:

import is from '@sindresorhus/is';

is.validLength(0); // => true
is.validLength(5); // => true
is.validLength(Number.MAX_SAFE_INTEGER); // => true
is.validLength(-1); // => false
is.validLength(1.5); // => false
is.validLength(Number.MAX_SAFE_INTEGER + 1); // => false
is.validLength('5'); // => false

// Useful for validating array-like objects
function createArrayLike(length: unknown) {
  if (is.validLength(length)) {
    // length is now typed as number and guaranteed to be valid
    const obj: any = {};
    obj.length = length;
    for (let i = 0; i < length; i++) {
      obj[i] = i;
    }
    return obj;
  }
  throw new Error('Invalid length');
}

Notes

  • Empty/non-empty object checks only consider enumerable properties using Object.keys()
  • Non-enumerable properties are ignored in object emptiness checks
  • Array-like includes strings, NodeLists, arguments objects, and any object with numeric indices and length
  • Tuple-like checking validates both length and type of each element
  • Valid length is useful for creating array-like objects and validating counts
  • All collection checks work with TypeScript type guards for compile-time type narrowing

Install with Tessl CLI

npx tessl i tessl/npm-sindresorhus--is

docs

assertions.md

async.md

collections.md

index.md

numbers.md

objects.md

primitives.md

strings.md

typed-arrays.md

validation.md

web-apis.md

tile.json