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

此生再无相见时 提交于 2020-02-27 06:34:11

问题


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:


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


来源:https://stackoverflow.com/questions/44080759/is-it-possible-to-constrain-a-generic-type-defined-in-a-jsdoc-template-declarat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!