实现说明
一个对象字面量承载 email、displayName、plan——每个值都就地写死。
常见问题
除了语言运行时还需要什么准备?
什么都不需要——语言运行时是唯一要求。
核心语句
type Keys = keyof AccountExport;
代码示例
interface Account {
id: string;
email: string;
displayName: string;
createdAt: Date;
plan: 'free' | 'pro';
}
// 创建:服务端生成 id 与时间戳
type CreateAccount = Omit<Account, 'id' | 'createdAt'>;
// 更新:所有可改字段都可选
type UpdateAccount = Partial<Pick<Account, 'email' | 'displayName' | 'plan'>>;
// 响应:对外暴露的字段子集
type AccountResponse = Pick<Account, 'id' | 'displayName' | 'plan'>;
// 必填化:导出时全部字段必须有值
type AccountExport = Required<Account>;
const created: CreateAccount = { email: 'a@b.c', displayName: 'Ada', plan: 'pro' };
const patch: UpdateAccount = { plan: 'free' };
const response: AccountResponse = { id: 'acc_1', displayName: 'Ada', plan: 'free' };
console.log(created, patch, response);
// 派生关系是活的:Account 增删字段,三个 DTO 自动跟随
type Keys = keyof AccountExport;