实现说明
逻辑集中在函数 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');