Core Utilities

Array Utilities

Advanced utilities for manipulating arrays and tuples in TypeScript. These types allow you to transform, filter, convert to union, and perform type-level operations on arrays in a safe and expressive way.

Array Utilities

Advanced utilities for manipulating arrays and tuples in TypeScript. These types allow you to transform, filter, convert to union, and perform type-level operations on arrays in a safe and expressive way.

Installation

npm i -D @halvaradop/ts-utility-types

Usage

import type { , ,  } from "@halvaradop/ts-utility-types/arrays"
import type * as  from "@halvaradop/ts-utility-types/arrays" 


type  = .
  • AllEquals
  • ArrayToUnion
  • Chunk
  • CompareArrayLength
  • ConstructTuple
  • Filter
  • FilterNonNullish
  • Flatten
  • HasDuplicates
  • Includes
  • IndexOf
  • LastIndexOf
  • Reverse
  • Size
  • Take
  • ToUnion
  • Uniques
  • Zip

For maximum type safety, use these utility types with the as const assertion. This ensures TypeScript infers the most precise literal types.

You can also combine these utilities to create advanced type-level operations and enhance type safety throughout your projects. See the Overview for more details.

ArrayToUnion<Array>

Creates a union type from the literal values of a constant string or number array. This is especially useful for representing a set of allowed values based on the array elements, such as enums, option lists, or discriminated unions.

ArgumentTypeDescription
Arrayunknown[]The tuple or readonly array to convert to a union type.

Related: ToUnion

import type {  } from "@halvaradop/ts-utility-types/arrays"

type Letters = <["foo", "bar", "foobar"]>
type Letters = "foo" | "bar" | "foobar"
type Numbers = <[1, 2, 3, 4, 5]>
type Numbers = 3 | 2 | 1 | 5 | 4
type Mixed = <["hello", 42, true]>
type Mixed = true | "hello" | 42

Size<Array>

Gets the length (size) of an array or tuple as a type. Returns the number of elements as a numeric literal type, or 0 if not an array.

ArgumentTypeDescription
Arrayunknown[]The array or tuple to get the length of.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type Length = <[1, 2, 3]>
type Length = 3
type StringArrayLength = <["a", "b", "c", "d"]>
type StringArrayLength = 4
type EmptyLength = <[]>
type EmptyLength = 0

Type Safety

Array utilities work with both tuples and arrays, but provide the most precise types when used with tuples.

Filter<Array, Predicate, Includes>

Filters the items of a tuple or array based on the provided predicate type. This is a powerful tool for extracting or removing specific values from a tuple at the type level.

ArgumentTypeDescription
Arrayunknown[]The array to filter.
PredicateunknownThe value(s) to filter by. Can be a single value or a union.
IncludesbooleanIf true (default), includes matching elements; if false, excludes them.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type OnlyTwo = <[1, 2, 3, 4, 5], [4, 5]>
type OnlyTwo = [4, 5]
type WithoutTwo = <[0, 1, 2], 2, false>
type WithoutTwo = [0, 1]
type WithoutFoo = <["foo", "bar", "foobar", 1, 2], "foo" | 2, false>
type WithoutFoo = ["bar", "foobar", 1]
type WithoutObj = <[{ : string }, { : number }, { : boolean }], { : number }, false>
type WithoutObj = [{
    foo: string;
}, {
    foobar: boolean;
}]

Reverse<Array>

Reverses the order of elements in a tuple type. The resulting tuple has the same elements as the input, but in reverse order.

ArgumentTypeDescription
Arrayunknown[]The array or tuple to reverse.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type Reversed = <[1, 2, 3]>
type Reversed = [3, 2, 1]
type ReversedAll = <[1, "foo", 2, "bar", { : number }, () => void]>
type ReversedAll = [() => void, {
    foo: number;
}, "bar", 2, "foo", 1]

IndexOf<Array, Match>

Returns the first index where the element Match appears in the tuple type Array. Returns -1 if not found. This is a type-level equivalent of JavaScript's Array.prototype.indexOf.

ArgumentTypeDescription
Arrayunknown[]The array or tuple to search.
MatchunknownThe element to search for.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type IndexNumber = <[string, 1, number, "a"], number>
type IndexNumber = 2
type IndexAny = <[string, 1, number, "a", any], any>
type IndexAny = 4

LastIndexOf<Array, Match>

Returns the last index where the element Match appears in the tuple type Array. Returns -1 if not found. This is a type-level equivalent of JavaScript's Array.prototype.lastIndexOf.

ArgumentTypeDescription
Arrayunknown[]The array or tuple to search.
MatchunknownThe element to search for.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type LastIndexNumber = <[2, 6, 3, 8, 4, 1, 7, 3, 9], 3>
type LastIndexNumber = 7
type LastIndexType = <[string, 2, number, "a", number, 1], number>
type LastIndexType = 4

ConstructTuple<Length, Value>

Creates a tuple with a defined size, where each element is of a specified type or value. Avoids TypeScript's deep instantiation errors for large tuples.

ArgumentTypeDescription
LengthnumberThe length of the tuple to create.
Valueunknown (default unknown)The value or type to fill the tuple with.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type ThreeX = <3, "x">
type ThreeX = ["x", "x", "x"]
type Strings = <5, string>
type Strings = [string, string, string, string, string]
type Fill = <5, 1>
type Fill = [1, 1, 1, 1, 1]

HasDuplicates<Array>

Checks if there are duplicated elements inside the tuple. Returns true if any value appears more than once, otherwise false.

ArgumentTypeDescription
Arrayunknown[]The array or tuple to check for duplicates.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type Duplicates = <[{ : string }, { : string }]>
type Duplicates = true
type DuplicatesWithFunctions = <[() => void, () => void]>
type DuplicatesWithFunctions = true

AllEquals<Array, Comparator>

Returns true if all elements within the tuple are equal to the provided Comparator type, otherwise returns false.

ArgumentTypeDescription
Arrayunknown[]The array or tuple to check.
ComparatorunknownThe value or type to compare all elements against.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type AllEqual = <[2, 2, 2], 2>
type AllEqual = true
type NonAllEquals = <[0, 0, 1, 0], 1>
type NonAllEquals = false
type WithUnion = <[1, 1, 2], 1 | 2>
type WithUnion = false

Chunk<Array, Length>

Splits a tuple into sub-tuples (chunks) of a specific length. If the last chunk is smaller than the specified length, it contains the remaining elements.

ArgumentTypeDescription
Arrayunknown[]The array or tuple to split.
LengthnumberThe length of each chunk.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type ChunksByTwo = <[1, 2, 3, 4, 5], 2>
type ChunksByTwo = [[1, 2], [3, 4], [5]]
type ChunksByFour = <[1, 2, 3, 4, 5], 4>
type ChunksByFour = [[1, 2, 3, 4], [5]]

Zip<Array1, Array2>

Combines two tuples into a tuple of pairs, element by element. The resulting tuple has the length of the shorter input tuple.

ArgumentTypeDescription
Array1unknown[]The first array or tuple.
Array2unknown[]The second array or tuple.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type Zipped = <[1, 2], ["a", "b"]>
type Zipped = [[1, "a"], [2, "b"]]
type ZippedStrsWithNumbers = <[1, "bar", 3], ["foo", 2]>
type ZippedStrsWithNumbers = [[1, "foo"], ["bar", 2]]
type ZippedWithObjs = <[{ : string }, { : string }], ["foo", "bar"]>
type ZippedWithObjs = [[{
    foo: string;
}, "foo"], [{
    bar: string;
}, "bar"]]

Flatten<Array>

Returns the innermost element type of a nested array, recursively flattening all levels. If the input is not an array, returns the input type.

ArgumentTypeDescription
Arrayunknown[]The array or nested array to flatten.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type Flattened = <number[][]>
type Flattened = number
type FlattenedString = <string[][][]>
type FlattenedString = string

CompareArrayLength<T, U>

Compares the length of two arrays or tuples. Returns 1 if the first is longer, -1 if the second is longer, and 0 if they are equal.

ArgumentTypeDescription
Tany[]The first array or tuple.
Uany[]The second array or tuple.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type Compare1 = <[1, 2, 3], [1, 2]>
type Compare1 = 1
type Compare2 = <[1, 2], [1, 2, 3]>
type Compare2 = -1
type Compare3 = <[1, 2, 3], [1, 2, 3]>
type Compare3 = 0

Uniques<Array>

Returns a tuple containing only the unique values from the input array, preserving the order of first appearance.

ArgumentTypeDescription
Arrayunknown[]The array or tuple to deduplicate.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type UniqueNumbers = <[1, 2, 3, 3, 4, 4, 5]>
type UniqueNumbers = [1, 2, 3, 4, 5]
type UniqueStrings = <["a", "b", "c", "a", "b"]>
type UniqueStrings = ["a", "b", "c"]
type AllDupes = <[1, 1, 1, 1]>
type AllDupes = [1]
type EmptyUnique = <[]>
type EmptyUnique = []

ToUnion<T>

Creates a union type from the literal values of a tuple or a single value. Accepts any type, not just arrays. This is a more general version of ArrayToUnion.

ArgumentTypeDescription
TunknownThe tuple or value to convert to a union type.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type TupleNumber = <1>
type TupleNumber = 1
type TupleString = <"foo">
type TupleString = "foo"
type TupleMultiple = <1 | ["foo" | "bar"]>
type TupleMultiple = 1 | "foo" | "bar" | []
type ArrayToUnionTest = <["a", "b", "c"]>
type ArrayToUnionTest = [] | "a" | "b" | "c"

Take<N, Array>

Extracts the first N elements from an array. If N is negative, extracts the last N elements. Handles out-of-bounds and empty arrays gracefully.

ArgumentTypeDescription
NnumberThe number of elements to extract. If negative, extracts from the end.
Arrayunknown[]The array or tuple to extract from.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type TakeFirst = <2, [1, 2, 3, 4]>
type TakeFirst = [1, 2]
type TakeLast = <-2, [1, 2, 3, 4]>
type TakeLast = [3, 4]
type TakeAll = <10, [1, 2]>
type TakeAll = [1, 2]
type TakeEmpty = <2, []>
type TakeEmpty = []

FilterNonNullish<Array>

Removes all nullish values (null or undefined) from the provided array. Also deeply filters nested objects using DeepNonNullish to ensure all nested properties are non-nullish.

ArgumentTypeDescription
Arrayunknown[]The array or tuple to filter.
import type {  } from "@halvaradop/ts-utility-types/arrays"

type Cleaned = <[1, null, 2, undefined, 3]>
type Cleaned = [1, 2, 3]
type NestedCleaned = <[[1, null], [undefined, 2], 3]>
type NestedCleaned = [[1, null], [undefined, 2], 3]
type AllNullish = <[null, undefined]>
type AllNullish = []
type NoNullish = <
type NoNullish = [{
    foo: string;
    bar: [{
        foobar: [{
            barbar: [];
        }];
    }];
}]
[{ : string; : [null, undefined, { : [null, undefined, { : [null, undefined] }] }] }] > type NonNullishWithObjs = <
type NonNullishWithObjs = [{
    foo: string;
}, {
    foo: {};
}]
[null, undefined, { : string; : undefined }, { : null; : { : undefined } }] >