示例工程 15-type-testing-api-design

15-type-testing-api-design/02-utility-type-tests/src/main.ts

typescript · 0.6 KB

运行:15 · utility-type-tests

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

// 演示:为工具类型写类型级回归测试
export interface User {
  id: number;
  name: string;
  email?: string;
}
 
export type UserPatch = Partial<Pick<User, 'name' | 'email'>>;
export type UserSummary = Readonly<Pick<User, 'id' | 'name'>>;
 
export function applyPatch(user: User, patch: UserPatch): User {
  return { ...user, ...patch };
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const user = applyPatch({ id: 1, name: 'Ada' }, { email: 'ada@example.com' });
  const lines = [`${user.id}:${user.name}:${user.email ?? '(none)'}`];
  for (const line of lines) {
    log(line);
  }
  return lines;
}