typescriptarraybuffersharedarraybuffer

What results in TextEncoder.encode() using a buffer of a given type?


The return value of TextEncoder.encode() is Uint8Array<ArrayBufferLike>. The ArrayBufferLike type includes ArrayBuffer and SharedArrayBuffer. How to know which type of array buffer encode() will use? Can it be configured? Why doesn't it just use ArrayBuffer?


Solution

  • I don't think there's ever a case where an instance of TextEncoder can create a new Uint8Array that's backed by a SharedArrayBuffer — the buffer property on the typed array returned by the encoder's encode method will always be an instance of ArrayBuffer — the WHATWG encoding spec describes the last step of TextEncoder#encode this way:

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


    TypedArrays were only very recently made generic (in TS version 5.7 released about a month ago / original PR) — before that, all typed arrays exclusively used the ArrayBufferLike type for the backing binary storage and couldn't be typed more narrowly.

    There are certainly cases where it's useful to have a SharedArrayBuffer — e.g. bring-your-own-buffer scenarios like the encodeInto method of a text encoder.

    This is likely just an oversight in the DOM lib types (source) and can/will be narrowed in the future.