问题描述
我们想使用jsDoc注释在常规.js文件中定义 mixin类而不是.ts文件.
We'd like to define mixin classes in regular .js files using jsDoc comments instead of .ts files.
mixin类的一个重要方面是使用extends
将泛型类型参数限制为类构造函数.例如,以上页面具有以下TypeScript:
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的jsDoc支持允许@template T
声明,但是我们看不到任何将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?
我们愿意创建/使用.d.ts
文件来支持此操作,只要mixin声明本身可以存在于.js文件中,并且checkJs
将适当地对该文件的类型进行检查. js文件.
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.
推荐答案
从TypeScript 2.9开始,现在似乎可以使用TypeScript来约束模板参数(请参见问题24600 ).因此,上面的TypeScript声明将变为:
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) { … }
这篇关于是否可以约束jsDoc @template声明中定义的泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!