Memento Pattern Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Memento Pattern runs in O(1) time and O(n) space, in TypeScript as in every other language.
- ✓The runtime tools are the JavaScript ones. What TypeScript adds is the ability to make the memento genuinely opaque: a branded or private-field type that the caretaker can hold but not read, which is the encapsulation the pattern describes and which no other language on this page enforces at compile time without a runtime cost.
- ✓Type the memento as an opaque branded type so only the originator can construct or destructure it; that is the compile-time version of the pattern intent and reviewers appreciate it because it removes the need for a convention.
- ✓The TypeScript trap: Readonly is shallow and DeepReadonly is a recursive conditional type that hits the compiler instantiation limit on a large state model, so the strong version of the guarantee is the one that stops compiling as the app grows.
- ✓No runtime cost from the types. The compile-time cost is concentrated in DeepReadonly and similar recursive mapped types over a large state tree, which is a well-known cause of slow editor completions; applying the mapping at one boundary rather than throughout the codebase keeps it bounded.
What Memento Pattern actually is
Memento Pattern in TypeScript: what you actually reach for
TypeScript implementation
declare const brand: unique symbol;
// Opaque: the caretaker can HOLD this and cannot read or forge it.
export type Memento = { readonly [brand]: 'editor' };
interface State { readonly text: string; readonly cursor: number }
export class Editor {
private state: State = { text: '', cursor: 0 };
save(): Memento {
return structuredClone(this.state) as unknown as Memento;
}
restore(m: Memento): void {
this.state = m as unknown as State; // only the originator may look inside
}
type(s: string): void {
this.state = { text: this.state.text + s, cursor: this.state.cursor + s.length };
}
}
const ed = new Editor();
const snap: Memento = ed.save();
// snap.text; // compile error: the caretaker cannot read it
ed.type('hello');
ed.restore(snap);
// Restored from disk: parse, never assert.
function parseMemento(raw: unknown): Memento {
if (typeof raw === 'object' && raw !== null && 'text' in raw && 'cursor' in raw) {
return raw as unknown as Memento;
}
throw new Error('memento from an incompatible version');
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Memento Pattern?
The runtime tools are the JavaScript ones. What TypeScript adds is the ability to make the memento genuinely opaque: a branded or private-field type that the caretaker can hold but not read, which is the encapsulation the pattern describes and which no other language on this page enforces at compile time without a runtime cost. Readonly and a recursive DeepReadonly express immutability, and unique symbol brands prevent a plain object being passed where a memento is expected.
What is the most common TypeScript mistake when implementing Memento Pattern?
Readonly is shallow and DeepReadonly is a recursive conditional type that hits the compiler instantiation limit on a large state model, so the strong version of the guarantee is the one that stops compiling as the app grows. Meanwhile structuredClone is typed as returning T while discarding the prototype, so a snapshot of a class instance type-checks as that class and is not one; the compiler actively helps you write the bug. Model the memento as data from the start rather than cloning the object.
How does Memento Pattern actually perform in TypeScript?
No runtime cost from the types. The compile-time cost is concentrated in DeepReadonly and similar recursive mapped types over a large state tree, which is a well-known cause of slow editor completions; applying the mapping at one boundary rather than throughout the codebase keeps it bounded. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.