maga
maga

Reputation: 720

Declaring types for mixin class

Not a TypeScript user, but I'm writing a TypeScript declaration file for my JavaScript library, and I'm stuck on the following code:

function ArrayMixin(Base) {
  class ExtendedArray extends Base {}
  return ExtendedArray;
}

This returns a class that extends a given class. In this case I'd like to limit the Base to Arrays and TypedArrays (so-called indexed collections). I can create a union type declaring all the necessary constructors and use it as type in the function signature:

type IndexedCollection = ArrayConstructor|Int8ArrayConstructor
declare function ArrayMixin(Base: IndexedCollection): ExtendedArray

But how do I specify that my ExtendedArray extends any of those in IndexedCollection? How do I declare ExtendedArray?

Upvotes: 3

Views: 91

Answers (2)

maga
maga

Reputation: 720

Researching more into generics, as Søren D. Ptæus suggested, led me to the following. In order to declare this JavaScript construction:

function ArrayMixin(Base) {
  class ExtendedArray extends Base {}
  return ExtendedArray;
}

We need this in the declaration file:

export declare class ExtendedArray {}

interface Constructor<T> {
    new (...args): T;
}

export declare function ArrayMixin<T extends IndexedCollection>(Base?: Constructor<T>):
 Constructor<T & ExtendedArray>;

Upvotes: 2

S&#248;ren D. Pt&#230;us
S&#248;ren D. Pt&#230;us

Reputation: 4542

You can use generic constraints to specify that your return type extends IndexedCollection like this:

declare function ArrayMixin<T extends IndexedCollection>(Base: IndexedCollection): T

Upvotes: 1

Related Questions