Optional Tuple Elements Type Argument Lists
Type argument lists with optional tuple elements, destructure defaults for missing entries, and keep optional elements at the end of the tuple.
Code
// Optional tuple elements describe trailing arguments in a type.
type Range = [start: number, end?: number];
type Job = [name: string, retries?: number, timeoutMs?: number];
function describe(range: Range): string {
const [start, end = start] = range;
return start + ".." + end;
}
const jobs: Job[] = [
["sync"],
["upload", 3],
["render", 2, 5000],
];
for (const [name, retries = 1, timeoutMs = 1000] of jobs) {
console.log(name, "retries=" + retries, "timeout=" + timeoutMs);
}
console.log(describe([5]));
console.log(describe([2, 9]));
const optionalTail: [string, number?] = ["ok"];
console.log("tail length:", optionalTail.length);Output
Captured from a sandboxed run of this snippet in the build pipeline.
sync retries=1 timeout=1000
upload retries=3 timeout=1000
render retries=2 timeout=5000
5..5
2..9
tail length: 1What the snippet does
Structurally, expect the function describe and nothing else.
for (const [name, retries = 1, timeoutMs = 1000] of jobs) is the loop that handles the per-item work.
Watch out for
- Dependency-free by construction — no registry, no lockfile entry.
Using it
The primary signature is function describe(range: Range)
Look for the tail length: prefixes when the file runs; they tie each line to its step.
Key statements
return start + ".." + end;
Interactive Tools for This Topic
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `describe` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.