示例工程 02-basic-types-inference

02-basic-types-inference/02-tuple-vs-array/src/main.ts

typescript · 0.7 KB

运行:02 · tuple-vs-array

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// 演示:元组固定长度与位置类型,数组则可变长
export type Point = [x: number, y: number];
export type LogEntry = [level: 'info' | 'warn', ...parts: string[]];
 
export function formatPoint(point: Point): string {
  return `(${point[0]}, ${point[1]})`;
}
 
export function formatEntry(entry: LogEntry): string {
  const [level, ...parts] = entry;
  return `[${level}] ${parts.join(' ')}`;
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const point: Point = [3, 4];
  const entries: LogEntry[] = [
    ['info', 'server', 'started'],
    ['warn', 'retry', 'in', '200ms'],
  ];
  const lines = [formatPoint(point), ...entries.map(formatEntry)];
  for (const line of lines) {
    log(line);
  }
  return lines;
}