Course contentsShow
← TypeScript
Lesson 1403 of 1,79632. Advanced PatternsFree lesson

Named Labels in Generic Tuples

Combine named tuple labels with generic type parameters to create reusable, well-documented tuple patterns.

Named Labels in Generic Tuples

What you'll learn: How to combine named tuple labels with generic type parameters to create reusable, well-documented tuple patterns.


Generic tuples become significantly more readable and maintainable when you add named labels to their elements. This combination allows you to build flexible, reusable type utilities that clearly communicate the purpose of each position in the tuple.

The Power of Combining Generics with Labels

When you use generic type parameters in tuple definitions, you create patterns that work across multiple types. Adding named labels to these generic positions transforms cryptic type signatures into self-documenting code.

// Without labels - unclear what each position represents
type Pair<T, U> = [T, U];

// With labels - crystal clear intent
type Coordinate<T, U> = [x: T, y: U];

const point: Coordinate<number, number> = [10, 20];
const mixed: Coordinate<string, boolean> = ["left", true];

Generic Tuple Utilities with Labels

This pattern shines when building reusable tuple manipulation utilities:

// Generic tuple wrapper with metadata
type Tagged<Label extends string, Value> = [tag: Label, value: Value];

const userTag: Tagged<"user", number> = ["user", 42];
const productTag: Tagged<"product", string> = ["product", "ABC123"];

// Generic result type
type Result<T, E> = [ok: true, value: T] | [ok: false, error: E];

function divide(a: number, b: number): Result<number, string> {
  if (b === 0) return [false, "Division by zero"];
  return [true, a / b];
}

Rest Elements in Generic Labeled Tuples

You can combine rest elements with generic types and labels for maximum flexibility:

type ApiResponse<Status extends number, ...Data extends unknown[]> = 
  [status: Status, ...data: Data];

const success: ApiResponse<200, string, number> = [200, "OK", 42];
const created: ApiResponse<201, { id: number }> = [201, { id: 5 }];

This pattern is especially valuable in library code where tuple shapes need to adapt to user-provided types while maintaining clear documentation about what each position represents.

Key Takeaway: Named labels in generic tuples combine the flexibility of generics with the clarity of labeled elements, creating reusable type patterns that are both powerful and self-documenting.