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

No differentiation between ArrayBuffer and Uint8Array #55032

Closed
lucacasonato opened this issue Jul 15, 2023 · 3 comments
Closed

No differentiation between ArrayBuffer and Uint8Array #55032

lucacasonato opened this issue Jul 15, 2023 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@lucacasonato
Copy link

Bug Report

TypeScript can not differentiate between ArrayBuffer and Uint8Array (or other typed array types).

const t: ArrayBuffer = new Uint8Array();

🔎 Search Terms

  • Structural typing
  • Brand checking

Related #50714, #42534, #202

🙁 Actual behavior

TypeScript checks the program above, and reports no errors.

🙂 Expected behavior

An error should be thrown, because in many APIs, passing a Uint8Array rather than an ArrayBuffer will throw or result in runtime errors.

Cause and proposed fix

The cause for this issue is TypeScript's structural typing. Within the type structure, ArrayBuffer is a subset of structure of Uint8Array. Because of this, TypeScript considers Uint8Array a valid ArrayBuffer type.

To fix this, we should consider adding a brand to the Uint8Array and ArrayBuffer interfaces, such as the following:

interface ArrayBuffer {
  readonly [Symbol.toStringTag]: "ArrayBuffer";
}

This may be an issue when subclassing ArrayBuffer, because the subclass may have a different Symbol.toStringTag

@MartinJohns
Copy link
Contributor

MartinJohns commented Jul 15, 2023

Duplicate of #42534, #31311, and ultimately #202.

See also this comment: #31311 (comment)

we briefly trialed using Symbol.toStringTag in this way, but making the buffers distinguishable actually breaks a number of people, apparently.

@lucacasonato
Copy link
Author

Oh I missed that comment. How unfortunate. I wonder if the breakage actually uncovers real user error...

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jul 17, 2023
@typescript-bot
Copy link
Collaborator

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants