TypeScript 4.0 Beta: Variadic Tuple Types

TypeScript 4.0 is a major milestone. The headline feature is Variadic Tuple Types, which finally allows strong typing for high-order functions like `concat` or `curry`. We explore this and Labeled Tuple Elements.

Variadic Tuple Types

You can now use spread syntax in generic tuple logic.

// Before TS 4.0: Had to overload for every length
function tail<T extends any[]>(arr: readonly [any, ...T]) {
    const [_ignored, ...rest] = arr;
    return rest;
}

// TS 4.0: Accurate type inference
const myTuple = [1, 2, 3, 4] as const;
const t = tail(myTuple); 
// t is inferred as [2, 3, 4] (typed tuple), not number[]

Labeled Tuple Elements

Tuples can now provide descriptive labels for documentation.

type Range = [start: number, end: number];

function createRange(...args: Range) {
    // args[0] is 'start', args[1] is 'end' in IntelliSense
}

Class Property Inference

class Square {
    // 4.0 infers 'area' is number type based on usage in constructor
    area;
    sideLength;

    constructor(sideLength: number) {
        this.sideLength = sideLength;
        this.area = sideLength ** 2;
    }
}

Key Takeaways

  • Variadic Tuples unlock sophisticated functional programming patterns.
  • Labeled tuples improve library documentation significantly.
  • Short-circuiting assignment operators (`||=`, `&&=`, `??=`) are also added.

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.