Sharp.toBuffer Response Types
Feature request
What are you trying to achieve?
In ES2024, ArrayBuffer and SharedArrayBuffer were extended, making them incompatible types. Consequently, TypeScript 5.7+ added type parameters to TypedArrays. And the Buffer type has the following interface:
interface Buffer<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike>
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/buffer.buffer.d.ts#L356
As a result now, the response currently obtained from toBuffer() is of type ArrayBufferLike. Assigning this to the BodyInit type defined in the Web Standard causes a type error.
If my analysis appears to be incorrect, this issue can be closed.
When you searched for similar feature requests, what did you find that might be related?
https://github.com/lovell/sharp/issues/4355
The above issue seems to discuss a similar perspective, though the main point of contention is likely memory management in Node.js? Sorry, I don't know C++, so I don't have technical insight into this issue.
What would you expect the API to look like?
Explicitly describe the ArrayBuffer in the return type Buffer.
- Promise<Buffer>
+ Promise<Buffer<ArrayBuffer>>
I don't understand the specific memory management context, but if responses using SharedArrayBuffer are supported, it would be desirable to return the response type appropriately.
What alternatives have you considered?
If this type error issue remains unresolved, I would likely work around it in my own product using type assertions for casting.
...type
ArrayBufferLike... Assigning this to theBodyInittype defined in the Web Standard causes a type error.
Did you see the following?
- https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-7.html#typedarrays-are-now-generic-over-arraybufferlike
- https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-9.html#libdts-changes
You probably want to use the .buffer property - see https://nodejs.org/docs/latest/api/buffer.html#bufbuffer
Thank you for response.
I hope this screen shot is helpful.
I use "sharp": "0.34.4", and "@types/node": "24.10.1",
If this is a misunderstanding on my part, please point it out.
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-9.html#libdts-changes says
the solution is to specify a more specific underlying buffer type instead of using the default ArrayBufferLike (i.e. explicitly writing out Uint8Array<ArrayBuffer> rather than a plain Uint8Array)
so perhaps try:
const buffer = await sharp(input).toBuffer();
const bodyInit: BodyInit = new Uint8Array(buffer);
I think this is the type level problem.
Using new Uint8Array(buffer) creates an unnecessary object since Buffer already extends Uint8Array. This adds runtime overhead and requires workarounds at every call.