← 中文资源

简体中文版本

可选元组元素标注参数列表

用可选元组元素标注参数列表,解构时为缺失项提供默认值,并把可选元素保留在元组末尾。

阅读英文原文

运行结果

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

sync retries=1 timeout=1000
upload retries=3 timeout=1000
render retries=2 timeout=5000
5..5
2..9
tail length: 1

实现说明

函数 describe是行为的来源,其余内容围绕它展开。 在这里做循环的是 for (const [name, retries = 1, timeoutMs = 1000] of jobs)。

使用要点

  • 跑完文件,输出里会留下标记——tail length:。

常见问题

有需要管理的依赖吗?

没有。无需声明或安装任何依赖。 文件在加载时定义 describe。

签名一览:function describe(range: Range)

核心语句

return start + ".." + end;

代码示例

// 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);