Mutex 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
- ✓Mutex Implementation runs in O(1) time and O(1) space, in TypeScript as in every other language.
- ✓The runtime primitives are the JavaScript ones. What TypeScript can add is a lock whose API makes the unguarded path unreachable: rather than exposing acquire and release, expose only a withLock<T>(fn: () => Promise<T>): Promise<T> and keep the protected state private, so the type system offers no way to touch the data outside the callback.
- ✓Wrap the guarded state in a class that holds it in a private field and exposes only methods that go through the lock.
- ✓The TypeScript trap: TypeScript can express "this function needs the lock" only by convention; there is no effect system, so a public field and a private lock still compile happily side by side.
- ✓Erased entirely; runtime cost is the promise-chain cost described for JavaScript. The one genuine consideration is that a withLock wrapper adds a closure allocation per call, which is irrelevant at request granularity and measurable in a tight loop, in the latter case the lock is usually the wrong design anyway.
What Mutex Implementation actually is
Mutex Implementation in TypeScript: what you actually reach for
TypeScript implementation
/** The guarded value is unreachable except through withLock, the closest
* TypeScript gets to Rust's "the mutex owns the data". */
export class Guarded<T> {
#value: T; // # is a RUNTIME private, unlike the private keyword
#tail: Promise<unknown> = Promise.resolve();
constructor(initial: T) { this.#value = initial; }
withLock<R>(fn: (value: T) => Promise<[T, R]>): Promise<R> {
const run = this.#tail.then(async () => {
const [next, result] = await fn(this.#value);
this.#value = next;
return result;
});
this.#tail = run.catch(() => undefined); // a throw must not wedge the chain
return run;
}
}
const account = new Guarded({ balance: 100 });
export const withdraw = (amount: number): Promise<number> =>
account.withLock(async (state) => {
if (state.balance < amount) throw new Error('insufficient');
const next = { balance: state.balance - amount };
return [next, next.balance];
});
// Note: the private and readonly keywords are ERASED. readonly stops assignment,
// not mutation, a readonly array can still be pushed to.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 Mutex Implementation?
The runtime primitives are the JavaScript ones. What TypeScript can add is a lock whose API makes the unguarded path unreachable: rather than exposing acquire and release, expose only a withLock<T>(fn: () => Promise<T>): Promise<T> and keep the protected state private, so the type system offers no way to touch the data outside the callback. That is the closest a structurally-typed language gets to Rust ownership.
What is the most common TypeScript mistake when implementing Mutex Implementation?
TypeScript can express "this function needs the lock" only by convention; there is no effect system, so a public field and a private lock still compile happily side by side. The specific TypeScript-flavoured trap is that readonly and private are compile-time only, private is erased at runtime (unlike a # field) and readonly prevents assignment, not mutation, so a readonly array can still be pushed to from outside the lock. Use # private fields and expose copies if the guarantee must survive to runtime.
How does Mutex Implementation actually perform in TypeScript?
Erased entirely; runtime cost is the promise-chain cost described for JavaScript. The one genuine consideration is that a withLock wrapper adds a closure allocation per call, which is irrelevant at request granularity and measurable in a tight loop, in the latter case the lock is usually the wrong design anyway. Time complexity is O(1) and space is O(1).
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 trialBefore paying for Devin, check its student and free-tier options 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.