fix(types): specify ArrayBuffer as a backing buffer type for TextEncoder.encode()#30434
Conversation
| /** @category Encoding */ | ||
| interface TextEncoder extends TextEncoderCommon { | ||
| /** Returns the result of running UTF-8's encoder. */ | ||
| encode(input?: string): Uint8Array; | ||
| encodeInto(input: string, dest: Uint8Array): TextEncoderEncodeIntoResult; | ||
| } |
There was a problem hiding this comment.
Removed this interface because it simply appears to be a duplicate with less document
|
I think this specific issue was fixed in TypeScript 5.9. We should wait for that before landing probably and wait for the minor release because this is breaking. https://devblogs.microsoft.com/typescript/announcing-typescript-5-9/#lib.d.ts-changes |
|
Since TypeScript 4.7, Personally, I don't feel the need to wait for TypeScript 4.9, but I don't have a strong opinion. |
|
This specific issue was only fixed recently in microsoft/TypeScript-DOM-lib-generator#1944 for TS 5.9, so I think we should wait in order to align (plus it's a breaking change) |
|
That's true. That makes sense 👍 |
|
oh ok thanks for the detail. let's wait for that |
This patch updates the
TextEncoderinterface type declarations to correctly specifyArrayBufferas the backing buffer type for theencode()method, aligning with the spec and addressing the change introduced in TypeScript 5.7 about makingArrayVBufferLikea default buffer type behindUint8Array.Problem
TypeScript 5.7 changed the default backing buffer type for
Uint8ArrayfromArrayBuffertoArrayBufferLike(which is a union ofArrayBufferandSharedArrayBuffer). However,TextEncoder.encode()per specification always returns aUint8Arraybacked by a standardArrayBuffer, never aSharedArrayBuffer. This mismatch causes type errors when passing the buffer to functions expectingArrayBuffer:Type check result with Deno v2.4.4:
Solution
This issue is resolved in this patch by explicitly specifying
Uint8Array<ArrayBuffer>as the return type forencode().Also, the second parameter type of
encodeInto()is updated toUint8Array<ArrayBufferLike>to make it less confusing and more explicit.Refs
TextEncoder.prototype.encodereturnUint8Array<ArrayBuffer>microsoft/TypeScript-DOM-lib-generator#1893Uint8Array<ArrayBuffer>microsoft/TypeScript-DOM-lib-generator#1944