TypeScript Tuple Type Utilities

5.0.1 · active · verified Sun Apr 19

typescript-tuple is a type-only utility library providing a rich set of generics for manipulating tuple types in TypeScript. The current stable version is 5.0.1. It offers various type-level operations, mimicking common array methods like `Append`, `Prepend`, `Reverse`, `Concat`, `Slice`, `Drop`, and `FillTuple`, but applied to static tuple types. This allows developers to enforce strict type safety and leverage advanced type inference when working with fixed-length or variable-length tuple structures, catching potential type mismatches at compile time rather than runtime. The library differentiates itself by focusing exclusively on type transformations, offering a comprehensive suite for tuple manipulation within TypeScript's type system itself, making it a powerful tool for complex type definitions and functional type programming.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates fundamental type-level tuple manipulations: appending an element, reversing a tuple's order, and concatenating two tuples, showing how the library provides powerful type-safety for array-like operations on fixed-length type structures.

import { Append, Reverse, Concat } from 'typescript-tuple';

// Define some base tuples with strict types
type MyTupleA = ['hello', 'world'];
type MyTupleB = [1, 2, 3];

// --- Example 1: Appending an element --- 
// Creates a new tuple type with an additional element at the end.
type AppendedTuple = Append<MyTupleA, '!'>;
// Expect: ['hello', 'world', '!']
const appendedInstance: AppendedTuple = ['hello', 'world', '!'];
console.log('Appended Tuple:', appendedInstance);

// --- Example 2: Reversing a tuple --- 
// Creates a new tuple type with elements in reverse order.
type ReversedTuple = Reverse<MyTupleB>;
// Expect: [3, 2, 1]
const reversedInstance: ReversedTuple = [3, 2, 1];
console.log('Reversed Tuple:', reversedInstance);

// --- Example 3: Concatenating two tuples --- 
// Merges two tuple types into a single new tuple type.
type ConcatenatedTuple = Concat<MyTupleA, MyTupleB>;
// Expect: ['hello', 'world', 1, 2, 3]
const concatenatedInstance: ConcatenatedTuple = ['hello', 'world', 1, 2, 3];
console.log('Concatenated Tuple:', concatenatedInstance);

// This library operates purely at the TypeScript type level. 
// The variables 'appendedInstance', 'reversedInstance', and 'concatenatedInstance' 
// are runtime examples of how values conforming to these derived types would look. 
// The type manipulations themselves do not generate any JavaScript runtime code.

view raw JSON →