Home > OS >  Extend typed array class in Typescript
Extend typed array class in Typescript

Time:09-16

I would like to extend a Javascript-typed array in Typescript. Specifically, I want to start with a regular Uint8Array and then initialize it with 1's (instead of 0's as per regular typed array) and add some extra methods. I would like to do this in a way such that the regular ways of instantiating typed arrays don't throw type errors, e.g. new SpecialArray([1, 2, 3]) and new SpecialArray(3) should both work as expected.

I've got something like this:

class SpecialArray extends Uint8Array {

   constructor(arg: number | number[]) {
      super(arg)
      this.fill(1)
   }
   
   ...

}

However, Typescript throws the following error about 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 found out I can get around this by using type assertions in the call to super:

super(arg as unknown as ArrayBufferLike)

However, this feels messy. Is there some clean way to do this?

CodePudding user response:

Or more simply, use the built-in ConstructorParameters type:

class SpecialArray extends Uint8Array {
   constructor(...args: ConstructorParameters<typeof Uint8Array>) {
      super(...args)
      this.fill(1)
   }
}

Playground

CodePudding user response:

The error gave a good hint. There is no version of Uint8Array that has a constructor taking number | number[].

Try

class SpecialArray extends Uint8Array {
  constructor(array: ArrayLike<number> | ArrayBufferLike) {
    super(array);
    this.fill(1)
  }
}
  • Related