Description
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.