I want to extend DataView
with state and functionality as follows:
export class MyDataView extends DataView
{
public position: number;
public constructor(buffer: ArrayBuffer | SharedArrayBuffer)
{
super(buffer);
}
public readInt32(): number
{
const result = this.getInt32(this.position);
this.position += 4;
return result;
}
}
I then try to create an instance as follows:
const fileSelector = document.getElementById("file-selector");
fileSelector.addEventListener("change", async (ev) =>
{
const fileList = (<HTMLInputElement>ev.target).files;
const arrayBuffer = await fileList[0].arrayBuffer();
const myDataView = new MyDataView(arrayBuffer);
});
However, I get the following error logged in the console:
Uncaught (in promise) TypeError: Constructor DataView requires 'new'
at MyDataView.DataView
at new MyDataView (s. below)
Going to the location marked by it shows the following JS code. I'm not sure if it is correct. In a similar JS-only issue, I saw that super()
should be called here instead of _super.call()
.
function MyDataView(buffer) {
var _this = this;
_this = _super.call(this, buffer) || this;
return _this;
}
How can I properly extend DataView
in TypeScript? What am I doing wrong?
The "target" in your tsconfig.json is probably set to "es5" and there is no ES5 way of extending ES6 classes, like Map, Set, or DataView.
(source: https://github.com/microsoft/TypeScript/issues/10853#issuecomment-246211140)
The solution that worked for me is that I've set "target" to "es6" and then the transpiled code went from:
var MyClass = /** @class */ (function (_super) {
__extends(BinaryIO, _super);
function BinaryIO(buffer, byteOffset, byteLength) {
var _this = _super.call(this, buffer, byteOffset, byteLength) || this;
_this.position = 0;
return _this;
}
...
}
to
class MyClass extends DataView {
constructor(buffer, byteOffset, byteLength) {
super(buffer, byteOffset, byteLength);
this.position = 0;
}
...
}