Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect type returned by TextEncoder.encode #60846

Open
aryzing opened this issue Dec 23, 2024 · 3 comments
Open

Incorrect type returned by TextEncoder.encode #60846

aryzing opened this issue Dec 23, 2024 · 3 comments

Comments

@aryzing
Copy link

aryzing commented Dec 23, 2024

πŸ”Ž Search Terms

TypedArray, Uint8Array, ArrayBufferLike, TextEncoder

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about TextEncoder

⏯ Playground Link

Playground link

πŸ’» Code

const data = new TextEncoder().encode("hello")
//    ^? Uint8Array<ArrayBufferLike>
// The `ArrayBufferLike` may include `SharedArrayBuffer`, but `encode()` 
// only supports `ArrayBuffer`, so this breaks code expecting an `ArrayBuffer`.

function processData(d: ArrayBuffer) {
  // do stuff
}

processData(data.buffer) // This should work, but reported as type error

πŸ™ Actual behavior

Values returned by TextEncoder.encode are not assignable to ArrayBuffer.

πŸ™‚ Expected behavior

Values returned by TextEncoder.encode should be assignable to ArrayBuffer.

Additional information about the issue

https://stackoverflow.com/a/79300250/1494725

@KisaragiEffective
Copy link

KisaragiEffective commented Dec 24, 2024

I think this is expected behavior change introduced in 5.7 series.
Consider change ArrayBuffer to ArrayBufferLike which is an union of both ArrayBuffer and SharedArrayBuffer.

@jcalz
Copy link
Contributor

jcalz commented Dec 24, 2024

This is definitely fallout from the TS5.7 change at #59417, but the question is whether it should be. Is TextEncoder.encode() known to produce a Uint8Array<ArrayBuffer>? I don't think it ever produces something else (there's encodeInto() that lets you bring your own buffer) but I'm no expert on these things. But if it is always producing a Uint8Array<ArrayBuffer> then it's probably best for the lib to reflect that. If it isn't, is that documented somewhere?

@aryzing
Copy link
Author

aryzing commented Dec 24, 2024

Surfacing a link from the linked SO post,

https://encoding.spec.whatwg.org/#ref-for-dom-textencoder-encode%E2%91%A0

If result is finished, then convert output into a byte sequence and return a Uint8Array object wrapping an ArrayBuffer containing output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants