Optional and Rest Elements with Labels
What you'll learn: How to combine tuple labels with optional (?) and rest (...) elements to create self-documenting, flexible tuple types.
You've learned that tuple labels make tuples more readable, but they become even more powerful when combined with optional and rest elements — turning cryptic type signatures into clear, self-documenting interfaces.
Combining Labels with Optional Elements
Just like you can have optional tuple elements, you can label those optional elements to explain what they represent when present:
type LogEntry = [timestamp: number, message: string, level?: string];
const error: LogEntry = [Date.now(), "Connection failed", "ERROR"];
const info: LogEntry = [Date.now(), "User logged in"]; // level is optional
The label level? tells readers "this third element, when present, represents the log level." Without the label, readers would see [number, string, string?] and wonder what that optional string means.
Combining Labels with Rest Elements
Rest elements can also be labeled to describe what the "rest" contains:
type Command = [action: string, ...args: string[]];
const saveCmd: Command = ["save", "file.txt", "backup.txt"];
const deleteCmd: Command = ["delete", "temp.txt"];
Here, ...args: string[] clearly documents that everything after the action is an argument list. This is far clearer than [string, ...string[]].
Real-World Pattern: Database Query Result
type QueryResult = [
success: boolean,
data?: unknown,
...errors: string[]
];
const success: QueryResult = [true, { id: 1, name: "Alice" }];
const failure: QueryResult = [false, undefined, "Network timeout", "Retry failed"];
The labels make it immediately clear: the first element is success status, optional data comes second, and any remaining elements are error messages.
Key Takeaway: Labeling optional and rest tuple elements transforms type signatures from cryptic notation into self-explanatory documentation, making complex function signatures and return types instantly understandable to your team.