← 中文资源

简体中文版本

递归构建固定长度元组类型

通过递归泛型 FixedTuple<T, N> 生成精确长度的元组类型,避免手写重复槽位,并结合运行时长度守卫校验定长向量。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

static rgb: rgb(255, 128, 0)
verified 3-tuple: rgb(10, 20, 30)
rejected length : 2
mac octets: 00:1a:2b:3c:4d:5e

实现说明

活动部件是函数 isFixedTuple、formatRgb。 循环只出现在 for (const sample of samples),它的每次迭代处理一个元素。

使用要点

  • 执行全篇示例的唯一基础前提条件就是本地装好该语言自带的工具链。
  • 跑完文件,输出里会留下标记——static rgb:、verified 3-tuple:、rejected length :。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 文件在加载时定义 isFixedTuple、formatRgb。

核心语句

return `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
return values.length === length;

代码示例

// 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(':'));