Producer-Consumer 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
- ✓Producer-Consumer Pattern runs in O(1) per op time and O(n) space, in TypeScript as in every other language.
- ✓The Web Streams API is the typed, cross-runtime option: ReadableStream<T>, WritableStream<T> and TransformStream<I, O> are generic, and a queuing strategy object (new CountQueuingStrategy({ highWaterMark })) makes the bound explicit and type-checked.
- ✓Model the queue as ReadableStream<Job> so the element type flows through every transform without casts, and make the shutdown signal part of the type rather than a magic sentinel, a discriminated union like { kind: "job"; job: Job } | { kind: "done" } turns "did I handle the sentinel?" into an exhaustiveness check the compiler performs.
- ✓The TypeScript trap: TypeScript will not catch the defining bug of this pattern, because unbounded growth is a runtime property and Array<T> is the same type at length 10 and length 10 million.
- ✓Types are erased; runtime behaviour is the JavaScript behaviour above. Web Streams carry slightly more per-chunk overhead than Node streams in Node itself because of the spec-mandated queuing and controller indirection, so for very hot Node-only paths the native stream remains faster, a real difference worth measuring rather than assuming parity.
What Producer-Consumer Pattern actually is
Producer-Consumer Pattern in TypeScript: what you actually reach for
TypeScript implementation
type Message<T> =
| { readonly kind: 'job'; readonly job: T }
| { readonly kind: 'done' };
// The bound is explicit AND type-checked.
function makeQueue<T>(source: AsyncIterable<T>, highWaterMark = 100): ReadableStream<Message<T>> {
return new ReadableStream<Message<T>>(
{
async pull(controller) {
for await (const job of source) {
controller.enqueue({ kind: 'job', job });
return;
}
controller.enqueue({ kind: 'done' });
controller.close();
},
},
new CountQueuingStrategy({ highWaterMark }),
);
}
async function consume<T>(stream: ReadableStream<Message<T>>, handle: (j: T) => Promise<void>) {
for await (const msg of stream as unknown as AsyncIterable<Message<T>>) {
switch (msg.kind) {
case 'job': await handle(msg.job); break;
case 'done': return;
default: {
const _exhaustive: never = msg; // a new variant becomes a COMPILE error
return _exhaustive;
}
}
}
}
void makeQueue; void consume;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) per op
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Producer-Consumer Pattern?
The Web Streams API is the typed, cross-runtime option: ReadableStream<T>, WritableStream<T> and TransformStream<I, O> are generic, and a queuing strategy object (new CountQueuingStrategy({ highWaterMark })) makes the bound explicit and type-checked. Node stream types from @types/node are generic in objectMode only loosely, so Web Streams generally give better inference for typed pipelines.
What is the most common TypeScript mistake when implementing Producer-Consumer Pattern?
TypeScript will not catch the defining bug of this pattern, because unbounded growth is a runtime property and Array<T> is the same type at length 10 and length 10 million. What it does catch, if you let it, is the sentinel bug: an untyped queue of Job | null forces a null check that people satisfy with a non-null assertion, whereas a discriminated union with a switch and a never-typed default makes an unhandled variant a compile error. Enable noFloatingPromises, since the most common producer-consumer defect in TypeScript is a missing await.
How does Producer-Consumer Pattern actually perform in TypeScript?
Types are erased; runtime behaviour is the JavaScript behaviour above. Web Streams carry slightly more per-chunk overhead than Node streams in Node itself because of the spec-mandated queuing and controller indirection, so for very hot Node-only paths the native stream remains faster, a real difference worth measuring rather than assuming parity. Time complexity is O(1) per op 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 trialIf you are a student, see what Replit offers students for free 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.