Skip to content

Uint8Array assignable to ArrayBuffer despite having subtle differences leading to browser TypeErrorsΒ #42534

Closed
@peaBerberian

Description

@peaBerberian

Bug Report

πŸ”Ž Search Terms

ArrayBuffer
Uint8Array

πŸ•— Version & Regression Information

At least in:

  • typescript 4.1.3
  • nightly

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

var a = new Uint8Array([1, 2, 3]);
new DataView(a);

Also, to be more explicit about the root issue in TypeScript:

function createDataView(buffer : ArrayBuffer) : DataView {
  return new DataView(buffer);
}

var a = new Uint8Array([1, 2, 3]);
createDataView(a);

πŸ™ Actual behavior

This is kind of continuation of the since closed due to inactivity #31311 issue, but with other arguments.

The sample codes presented here go through TypeScript's checks despite both leading to a browser TypeError because DataView's constructor expects an ArrayBuffer, not an Uint8Array (on FireFox, the error is: TypeError: DataView: expected ArrayBuffer, got Uint8Array).

From the linked issue, it seems that TypeScript considers an Uint8Array to be a valid ArrayBuffer because they are structurally the same. But there are subtle differences like this one.

I understand the point of view that TypeScript is not supposed to be perfectly sound, but I think that it would be nice if TypeScript caught those types of mistakes.

We had an issue related to this and I think that we wouldn't have it with plain JavaScript, because we would have been more careful with types! In the end, not always thinking about these types of mistakes is a major reason for switching to TS.

πŸ™‚ Expected behavior

I would expect that an ArrayBuffer and a Uint8Array to not be considered the same thing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions