Skip to content
jshacks.dev
TypeScript

Type Node.js streams

Type a Node.js Transform stream and pipe it with the promise version of pipeline so chunk types and errors are checked. Needs @types/node 22 or later.

1 min read
Summarize in AI

Streams are easy to wire wrongly. The types in @types/node document what each stage takes, and pipeline from node:stream/promises handles errors and cleanup.

upper.tsTypeScript
import { Readable, Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';

const upper = new Transform({
  objectMode: true,
  transform(chunk: string, _encoding, callback) {
    callback(null, chunk.toUpperCase());
  },
});

async function main(): Promise<void> {
  await pipeline(Readable.from(['ada', 'grace']), upper, async function* (source) {
    for await (const chunk of source) {
      console.log(chunk);
    }
  });
}

main();
Text
ADA
GRACE

objectMode: true makes each chunk one string, so chunk: string is accurate; in the default byte mode chunks are Buffer or strings, and the callback parameter must be typed accordingly. The last stage is an async generator, which pipeline accepts as a destination. See [stream.pipeline](https://nodejs.org/docs/latest-v24.x/api/stream.html#streampipelinesource-transforms-destination-options).

The annotation on chunk is an assertion, not a check: TypeScript cannot prove what the previous stage emits. If a stage can send other types, validate inside the transform. Use pipeline, not .pipe(), because .pipe() does not forward errors.

Also inNode.js
Share

More snippets

Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read
TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.