Mapped Type Modifiers Toggle readonly And Optional
Use mapped type modifiers to add or remove readonly and optional flags, producing mutable, locked, and key-filtered variants of one model.
Code
interface Account {
readonly id: string;
readonly owner: string;
nickname?: string;
email?: string;
}
// Mapped type modifiers: -readonly removes, -? makes keys required
type Mutable<T> = { -readonly [K in keyof T]-?: T[K] };
// +readonly / +? explicitly add modifiers back
type Locked<T> = { +readonly [K in keyof T]+?: T[K] };
// Filter to optional keys only, then require them
type OptionalKeys<T> = { [K in keyof T as undefined extends T[K] ? K : never]-?: T[K] };
const draft: Mutable<Account> = {
id: 'a-1',
owner: 'ada',
nickname: 'ace',
email: '[email protected]',
};
draft.id = 'a-2';
draft.nickname = 'ada';
const locked: Locked<Account> = { id: 'a-3' };
// locked.id = 'a-4'; // 只读,编译错误
const optional: OptionalKeys<Account> = { nickname: 'ace', email: '[email protected]' };
console.log(draft.id, locked.id, Object.keys(optional).join(','));Output
Captured from a sandboxed run of this snippet in the build pipeline.
a-2 a-3 nickname,emailUnder the hood
The top-level object literal pins id, owner, nickname, email as plain values — no derivation, no imports behind them.
Statements that matter
type OptionalKeys<T> = { [K in keyof T as undefined extends T[K] ? K : never]-?: T[K] };
type Mutable<T> = { -readonly [K in keyof T]-?: T[K] };
type Locked<T> = { +readonly [K in keyof T]+?: T[K] };
Interactive Tools for This Topic
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit.
Report a problem with this exampleOpens a pre-filled issue on GitHub.