示例工程 12-variance-soundness

12-variance-soundness/02-function-variance/src/main.ts

typescript · 0.6 KB

运行:12 · function-variance

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

// 演示:函数参数是逆变的(strictFunctionTypes),更窄的参数不能接收更宽的值
export type Animal = { name: string };
export type Dog = Animal & { bark(): void };
 
export function handleAnimal(handler: (animal: Animal) => void): string {
  handler({ name: 'generic animal' });
  return 'handled';
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const lines: string[] = [];
  const result = handleAnimal((animal) => {
    lines.push(`animal:${animal.name}`);
  });
  lines.push(result);
  for (const line of lines) {
    log(line);
  }
  return lines;
}