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

15-type-testing-api-design/02-utility-type-tests/types.test-d.ts

typescript · 0.7 KB

运行:15 · utility-type-tests

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

type Equal<A, B> =
  (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
 
import type { User, UserPatch, UserSummary } from './src/main.js';
 
// Partial<Pick<...>> 的精确形状
type Case1 = Expect<Equal<UserPatch, { name?: string; email?: string }>>;
 
// Readonly<Pick<...>> 的精确形状
type Case2 = Expect<Equal<UserSummary, { readonly id: number; readonly name: string }>>;
 
// 工具类型不会改变源类型
type Case3 = Expect<Equal<keyof User, 'id' | 'name' | 'email'>>;
 
// 负例:patch 不能添加未知字段
// @ts-expect-error: role 不在 UserPatch 中
const bad: UserPatch = { role: 'admin' };
 
export { bad };