Utility Types Deriving DTO Variants
Derive create, update, and response DTOs from one domain type with Pick, Omit, Partial, and Required so they never drift apart.
Code
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;Output
Captured from a sandboxed run of this snippet in the build pipeline.
{ email: 'a@b.c', displayName: 'Ada', plan: 'pro' } { plan: 'free' } { id: 'acc_1', displayName: 'Ada', plan: 'free' }How it works
One object literal carries email, displayName, plan — every value is written inline.
Account is the single source: id and createdAt are server-owned, email, displayName, and plan are editable, and plan narrows to the union 'free' | 'pro'. CreateAccount is Omit<Account, 'id' | 'createdAt'>, so the create payload keeps exactly the three editable fields, as the created literal demonstrates. UpdateAccount is Partial<Pick<Account, 'email' | 'displayName' | 'plan'>>, making every editable field optional — patch supplies only plan. AccountResponse picks id, displayName, and plan for the outward shape, and AccountExport applies Required<Account> so all five fields must be present. The closing Keys alias is keyof AccountExport, which keeps the derived keys tied to the domain type.
Core lines
type Keys = keyof AccountExport;
Interactive Tools for This Topic
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement.
Report a problem with this exampleOpens a pre-filled issue on GitHub.