microsoft/TypeScript

Incorrect inference for Uint8Array's underlying source

Closed this issue ยท 3 comments

๐Ÿ”Ž Search Terms

uint8array, arraylike, sharedarraybuffer

๐Ÿ•— Version & Regression Information

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

โฏ Playground Link

https://www.typescriptlang.org/play/?ts=6.0.0-dev.20251022#code/GYVwdgxgLglg9mABAUwB4EMC2AHANsgClQC5EBBAJwvQE8AhEYYZCgGRgGtlEAfcq2uy4AeMCEwAjFgD4AlKQCqMMFAAclajWEbaDJiyHJpiAN4AoRIgrIoICkjDIA7oiUr1AmkVlmAvkA

๐Ÿ’ป Code

function example(x: ArrayBufferLike | ArrayLike<number>): Uint8Array<ArrayBufferLike> {
  return new Uint8Array(x)
}

๐Ÿ™ Actual behavior

The example function can take an ArrayBuffer, SharedArrayBuffer or a number[] to wrap it in a Uint8Array, but due to ArrayLike<number>, the Uint8Array constructor incorrectly assumes the underlying source will be an ArrayBuffer and rejects x being passed in since it can also be a SharedArrayBuffer.

๐Ÿ™‚ Expected behavior

The expected behaviour is for the Uint8Array constructor to assume the underlying source will be ArrayBufferLike and not ArrayBuffer.

Additional information about the issue

No response

jcalz commented

Seems like #14107 is the underlying issue here; TS has two separate overloads for ArrayBufferLike and ArrayLike<number>, and you cannot call both of them at once. I doubt there's much appetite to add even more complicated construct signatures to handle these edge cases. If you need this yourself you can always just use declaration merging in your own code base like

interface Uint8ArrayConstructor {
  new <T extends ArrayBufferLike | Iterable<number> | ArrayLike<number> | number>(buffer: T):
    Uint8Array<T extends ArrayBufferLike ? T : ArrayBuffer>;
}

and then your code will just work.
Playground link to code

๐Ÿค– Thank you for your issue! I've done some analysis to help get you started. This response is automatically generated; feel free to ๐Ÿ‘ or ๐Ÿ‘Ž this comment according to its usefulness.

Similar Issues

Here are the most similar issues I found

If your issue is a duplicate of one of these, feel free to close this issue. Otherwise, no action is needed.

This issue has been marked as "Design Limitation" and has seen no recent activity. It has been automatically closed for house-keeping purposes.