← 中文资源

简体中文版本

非空元组类型保证首元素存在

用 [T, ...T[]] 把“至少一个元素”写进类型:first 返回 T 而不是 T | undefined,空数组在编译期就被拒绝,运行时不再需要判空。

阅读英文原文

运行结果

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

21.5
auth
batch: 1 2 3
single: 9

实现说明

逻辑集中在函数 first、logReadings里。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 first、logReadings。

核心语句

return `${label}: ${values.join(' ')}`;
return items[0];

代码示例

type NonEmptyArray<T> = [T, ...T[]];

// A non-empty tuple guarantees a first element, so first() returns T
// instead of T | undefined — no guard needed at the call site.
function first<T>(items: NonEmptyArray<T>): T {
  return items[0];
}

// A rest parameter typed [T, ...T[]] rejects calls with zero values
// at compile time, before the log line can ever come out empty.
function logReadings(label: string, ...values: NonEmptyArray<number>): string {
  return `${label}: ${values.join(' ')}`;
}

const readings: NonEmptyArray<number> = [21.5, 22.1, 20.9];
console.log(first(readings));

const queue: NonEmptyArray<string> = ['auth', 'sync', 'report'];
console.log(first(queue));

console.log(logReadings('batch', 1, 2, 3));
console.log(logReadings('single', 9));

// Both of these fail compilation, not at runtime:
// const empty: NonEmptyArray<number> = [];
// logReadings('no values');