示例工程 06-generics

06-generics/01-inference-from-arguments/src/main.ts

typescript · 0.6 KB

运行:06 · inference-from-arguments

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

// 演示:泛型参数可以从实参推断,也可以显式指定
export function pair<A, B>(first: A, second: B): [A, B] {
  return [first, second];
}
 
export function repeat<T>(value: T, times: number): T[] {
  return Array.from({ length: times }, () => value);
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const inferred = pair(1, 'a');
  const explicit = pair<string, number>('x', 1);
  const lines = [
    inferred.join(':'),
    explicit.join(':'),
    repeat('ab', 2).join('|'),
  ];
  for (const line of lines) {
    log(line);
  }
  return lines;
}