Home > Software design >  Specifying a list of valid constructors as an argument type in TypeScript
Specifying a list of valid constructors as an argument type in TypeScript

Time:10-19

I have some JavaScript (simplified) like this

function createTypedArray(data, TypedArrayConstructor) {
  return new TypedArrayConstructor(data);
}

Which you can call like this

const f32 = createTypedArray([1, 2, 3], Float32Array);
const u8 = createTypedArray([4, 5, 6], Uint8Array);

How can I specify the type of TypedArrayConstructor this in typescript? (note: I'm not worried about the return type).

I think the best solution would mean typescript would complain if it's not actually a typedarray constructor.

class NotTypedArray {
  constructor(...args) {  }  // assume typed to match signature of typedarrays
}

const nta = createTypedArray([1, 2, 3], NotTypedArray); // error?

But that's not a requirement, mostly a nice to have. Ideally it would be typed in such a way that intellisense could suggest types that fit.

CodePudding user response:

You can use a constructor signature:

function createTypedArray<T>(data: number[], TypedArrayConstructor: new (dat: number[]) => T) {
  return new TypedArrayConstructor(data);
}


const f32 = createTypedArray([1, 2, 3], Float32Array);
const u8 = createTypedArray([4, 5, 6], Uint8Array);

Playground Link

I also added a generic type parameter for a correct return type

CodePudding user response:

This works for my needs

type TypedArrayConstructor = 
   Int8ArrayConstructor | 
   Uint8ArrayConstructor | 
   Uint8ClampedArrayConstructor |
   Int16ArrayConstructor | 
   Uint16ArrayConstructor | 
   Int32ArrayConstructor | 
   Uint32ArrayConstructor | 
   Float32ArrayConstructor |
   Float64ArrayConstructor ;

function createTypedArray(data: number[], TypedArrayConstructor: TypedArrayConstructor) {
  return new TypedArrayConstructor(data);
}

const f32 = createTypedArray([1, 2, 3], Float32Array);
const u8 = createTypedArray([4, 5, 6], Uint8Array);
const a = createTypedArray([4, 5, 6], Array);  // error! (yay!)

I didn't know the constructors for typedarrays were predefined

Playground link

  • Related