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.
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.
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();ADA
GRACEobjectMode: 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.