1

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?

2 Answers 2

5

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

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

Playground

Sign up to request clarification or add additional context in comments.

1 Comment

Learn something new every day. How did I miss that? Gold!
1

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)
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.