#Make Readable.read() return Buffer
14 messages · Page 1 of 1 (latest)
You can specify the type of data returned by a Node.js Readable stream by using generics.
When you create a Readable stream, use Readable<Buffer> to indicate it should work with buffers.
For example: const stream = new Readable<Buffer>({...}).
Now, when you call stream.read(), TypeScript will infer the return type as Buffer instead of any.
This approach ensures type safety and better IntelliSense in your code.
I can’t use Readable<Buffer>
I am on Deno with @types/node though
My Readable from node:stream isn’t a generic
@round mist You can't change the runtime behavior via generics anyway
It looks like the output of read depends mutable internal stuff so it's not really possible for the method to automatically return the 'right' type.
I'm not sure why it returns any - if I'm reading this right, it seems like string | Buffer | null would be correct...
(method) Stream.Readable.read(size?: number): any
Thereadable.read()method reads data out of the internal buffer and returns it. If no data is available to be read,nullis returned. By default, the data is returned as a Buffer object unless an encoding has been specified using thereadable.setEncoding()method or the stream is operating in object mode.
... but maybe it can return other things?
But either way, you're either going to have to check that it's a buffer or just use a type assertion to assert that it's a buffer.