简体   繁体   中英

Extend typed array class in Typescript

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, eg 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?

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

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

Playground

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

Try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM