Looking to expand a Javascript-typed array in Typescript by taking a regular Uint8Array and initializing it with 1's, rather than the usual 0's. Additionally, I want to incorporate some extra methods without causing type errors when instantiating the typed arrays, such as new SpecialArray([1, 2, 3])
and new SpecialArray(3)
.
This is what I have so far:
class SpecialArray extends Uint8Array {
constructor(arg: number | number[]) {
super(arg)
this.fill(1)
}
...
}
However, Typescript throws an error regarding arg
:
No overload matches this call.
The last overload gave the following error.
Argument of type 'number | number[]' is not assignable to parameter of type 'ArrayBufferLike'.
Type 'number' is not assignable to type 'ArrayBufferLike'.ts(2769)
I discovered that I can work around this issue by using type assertions in the super call:
super(arg as unknown as ArrayBufferLike)
Nevertheless, this approach feels cumbersome. Is there a cleaner solution?