Skip to main content

tuple

Head, Tail, Last, Prepend, Append, Length, Zip.

import type {
  Head, Tail, Last,
  Prepend, Append,
  Length, Zip,
} from '@gentleduck/ttest/tuple'
type Head<T extends unknown[]> = T extends [infer H, ...unknown[]] ? H : never
type a = Head<[1, 2, 3]>  // 1
type b = Head<[]>         // never

Tail

type Tail<T extends unknown[]> = T extends [unknown, ...infer R] ? R : never
type a = Tail<[1, 2, 3]>  // [2, 3]

Last

type Last<T extends unknown[]> = T extends [...unknown[], infer L] ? L : never
type a = Last<[1, 2, 3]>  // 3

Prepend / Append

type Prepend<E, T extends unknown[]> = [E, ...T]
type Append <T extends unknown[], E> = [...T, E]
type a = Prepend<0, [1, 2]>  // [0, 1, 2]
type b = Append <[1, 2], 3>  // [1, 2, 3]

Length

type Length<T extends unknown[]> = T['length']
type a = Length<[1, 2, 3]>  // 3

Zip

type Zip<T extends unknown[], U extends unknown[]>

Pair T and U element-wise; stop at the shorter input.

type a = Zip<[1, 2, 3], ['a', 'b', 'c']>  // [[1, 'a'], [2, 'b'], [3, 'c']]
type b = Zip<[1, 2, 3], ['a']>            // [[1, 'a']]