Thread Pool 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
- ✓Thread Pool runs in O(1) submit time and O(n) space, in TypeScript as in every other language.
- ✓The runtime options are the JavaScript ones; TypeScript adds type safety across the worker boundary, which is where untyped worker code fails most often.
- ✓Declare one exported type for the request and one for the response, and use them on BOTH sides of the boundary so a change to the payload shape breaks the worker at compile time rather than at runtime.
- ✓The TypeScript trap: postMessage is typed as accepting any in the DOM and Node type definitions, so absolutely nothing type-checks across the boundary by default, a renamed field compiles cleanly on both sides and fails at runtime as undefined.
- ✓Erased at runtime, identical cost to JavaScript. One build-time note: workers run their own module graph, so a worker entry that imports a large shared barrel file pays the parse and evaluate cost in every worker; keeping worker entry points narrow measurably reduces startup, which is the dominant cost in worker pools.
What Thread Pool actually is
Thread Pool in TypeScript: what you actually reach for
TypeScript implementation
// protocol.ts: ONE type, imported by both sides.
export type Request =
| { readonly kind: 'hash'; readonly data: ArrayBuffer }
| { readonly kind: 'parse'; readonly text: string };
export type Response =
| { readonly kind: 'ok'; readonly value: string }
| { readonly kind: 'err'; readonly message: string };
// pool.ts
import Piscina from 'piscina';
const pool = new Piscina<Request, Response>({
filename: new URL('./worker.js', import.meta.url).href,
maxThreads: 8,
});
export async function hash(data: ArrayBuffer): Promise<string> {
const res = await pool.run({ kind: 'hash', data }, { transferList: [data] });
if (res.kind === 'err') throw new Error(res.message);
return res.value;
}
// worker.ts
export default function handle(req: Request): Response {
switch (req.kind) {
case 'hash': return { kind: 'ok', value: String(req.data.byteLength) };
case 'parse': return { kind: 'ok', value: req.text.trim() };
default: {
const _exhaustive: never = req; // new variant = COMPILE error
return { kind: 'err', message: String(_exhaustive) };
}
}
}
// Structured clone does NOT preserve prototypes: a class instance arrives
// as a plain object. instanceof fails even though the type says otherwise.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) submit
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Thread Pool?
The runtime options are the JavaScript ones; TypeScript adds type safety across the worker boundary, which is where untyped worker code fails most often. Piscina is generic, new Piscina<TaskInput, TaskResult>(), so run() returns a typed promise. For hand-rolled workers, the message channel is typed only if you declare a protocol type and cast at the two boundaries, because postMessage accepts any.
What is the most common TypeScript mistake when implementing Thread Pool?
postMessage is typed as accepting any in the DOM and Node type definitions, so absolutely nothing type-checks across the boundary by default, a renamed field compiles cleanly on both sides and fails at runtime as undefined. The other structural surprise is that structured clone does NOT preserve class identity: an instance arrives as a plain object with the same fields, so instanceof fails and methods are gone, even though the TypeScript type says otherwise. Types describe the shape, not the prototype.
How does Thread Pool actually perform in TypeScript?
Erased at runtime, identical cost to JavaScript. One build-time note: workers run their own module graph, so a worker entry that imports a large shared barrel file pays the parse and evaluate cost in every worker; keeping worker entry points narrow measurably reduces startup, which is the dominant cost in worker pools. Time complexity is O(1) submit 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 trialBefore paying for GitHub Copilot, 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.