Build Fixed-Length Tuple Types Recursively
Generate exact-arity tuple types with a recursive FixedTuple<T, N> alias and pair it with a runtime length guard for RGB vectors and byte blocks.
Code
// Build an exact N-element tuple recursively instead of repeating T by hand
type FixedTuple<
T,
N extends number,
Acc extends readonly T[] = [],
> = Acc['length'] extends N ? Acc : FixedTuple<T, N, readonly [...Acc, T]>;
type RgbColor = FixedTuple<number, 3>;
type MacOctets = FixedTuple<string, 6>;
function isFixedTuple<T, N extends number>(
values: readonly T[],
length: N,
): values is FixedTuple<T, N> & readonly T[] {
return values.length === length;
}
function formatRgb(rgb: RgbColor): string {
return `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
}
const primary: RgbColor = [255, 128, 0];
// const tooShort: RgbColor = [255, 128]; // Compile error: requires 3 elements
console.log('static rgb:', formatRgb(primary));
const samples: readonly number[][] = [[10, 20, 30], [10, 20]];
for (const sample of samples) {
if (isFixedTuple(sample, 3)) {
console.log('verified 3-tuple:', formatRgb(sample));
} else {
console.log('rejected length :', sample.length);
}
}
const mac: MacOctets = ['00', '1a', '2b', '3c', '4d', '5e'];
console.log('mac octets:', mac.join(':'));Output
Captured from a sandboxed run of this snippet in the build pipeline.
static rgb: rgb(255, 128, 0)
verified 3-tuple: rgb(10, 20, 30)
rejected length : 2
mac octets: 00:1a:2b:3c:4d:5eExecution summary — Build Fixed-Length Tuple Types Recursively
Build Fixed-Length Tuple Types Recursively is built around the functions isFixedTuple and formatRgb.
The loop for (const sample of samples) is the only repeated construct.
Caveats
- Sole prerequisite for execution remains having the stock language toolchain installed locally.
Applying it
The demo output is labeled (static rgb:, verified 3-tuple:, rejected length :); each label names the call that printed it.
Statements that matter
return `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
return values.length === length;
Interactive Tools for This Topic
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `isFixedTuple`, `formatRgb` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.