Mapped Types Key Remapping

Derive DTO and handler types from a domain type with mapped types and as-clause remapping so renames propagate automatically.

TypescriptData Integrity

Code

typescriptsnippet
32 lines
interface User {
  id: string;
  displayName: string;
  email: string;
}

// 同构映射:每个属性变为可空版本(表单草稿形态)
type UserDraft = { [K in keyof User]: User[K] | null };

// as 重映射:键名改写 + 值类型改写,DTO 由领域类型派生
type UserApi = {
  [K in keyof User as `user_${K}`]: K extends 'id' ? number : string;
};

// 过滤:as never 移除不需要的键
type PublicUser = { [K in keyof User as K extends 'email' ? never : K]: User[K] };

type Checks = [
  ExpectEqual<UserDraft['email'], string | null>,
  ExpectEqual<UserApi['user_id'], number>,
  ExpectEqual<keyof PublicUser, 'id' | 'displayName'>,
];
type ExpectEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2
  ? true
  : never;

const draft: UserDraft = { id: 'u1', displayName: null, email: null };
const api: UserApi = { user_id: 1, user_displayName: 'Ada', user_email: 'a@b.c' };
const publicUser: PublicUser = { id: 'u1', displayName: 'Ada' };
console.log(draft, api, publicUser);

type _ = Checks;

Output

Captured from a sandboxed run of this snippet in the build pipeline.

{ id: 'u1', displayName: null, email: null } { user_id: 1, user_displayName: 'Ada', user_email: 'a@b.c' } { id: 'u1', displayName: 'Ada' }

How the pieces fit together

The top-level object literal pins id, displayName, email as plain values — no derivation, no imports behind them.

Statements that matter

type PublicUser = { [K in keyof User as K extends 'email' ? never : K]: User[K] };
[K in keyof User as `user_${K}`]: K extends 'id' ? number : string;
type UserDraft = { [K in keyof User]: User[K] | null };

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching.