'How to create a generic buffer in TypeScript?
I have the following class:
export class BufferData {
arr: Float32Array;
index: number;
constructor() {
this.arr = new Float32Array(8);
this.index = 0;
}
maybeResize() {
let curArr = this.arr;
if (this.index < curArr.length) {
return;
}
let newArr = new Float32Array(curArr.length * 2);
for (let i = 0; i < curArr.length; i++) {
newArr[i] = curArr[i];
}
this.arr = newArr;
}
push(val: number) {
this.maybeResize();
this.arr[this.index++] = val;
}
}
This works, but I would like to make it generic if possible. That is, I'd like the signature of the class to be something like:
export class BufferData<T extends TypedArray>
Such that all instances of Float32Array in the above code would be replaced with T and I would be able to create one like this:
let buffer = new BufferData<Float32Array>();
However, I could not find whether or not Float32Array had a parent. Also, when I tried to do something like:
this.arr = new T(8);
in the constructor, it told me T was a type and not a value.
Is this sort of thing possible? Or do I have to just duplicate the class for each concrete type I wish to use it with?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
