Is it possible to constrain a generic type defined in a jsDoc @template declaration?

Viewed 1889

We'd like to define mixin classes in regular .js files using jsDoc comments instead of .ts files.

An important aspect of mixin classes is constraining the generic type parameter to a class constructor using extends. E.g., the above page has the following TypeScript:

type Constructor<T> = new(...args: any[]) => T;
function Tagged<T extends Constructor<{}>>(Base: T) { ... }

TypeScript's jsDoc support allows for a @template T declaration, but we don't see any way to constrain T to, for example, be a class constructor. Is there some way to do that?

We'd be willing to create/use .d.ts files to support this, as long as the mixin declaration itself can exist in a .js file, and that checkJs will appropriately type-check the workings of that .js file.

1 Answers

As of TypeScript 2.9 it seems constraining template parameters is now possible using TypeScript (see issue 24600). The above TypeScript declaration would therefor become:

/**
 * @template T
 * @typedef {new(...args: any[]) => T} Constructor
 **/

/**
 * @template {Constructor<{}>} T
 * @param {T} Base
 */
function Tagged(Base) { … }
Related