gpt4 book ai didi

javascript - 在 typescript 中为泛型函数编写 JSdoc

转载 作者:可可西里 更新时间:2023-11-01 02:47:52 26 4
gpt4 key购买 nike

我用以下代码提炼出了我的问题的本质:

full source

我有基类,派生类,Derived2:

class Base {
static get type() {
return 'Base';
}
}

class Derived extends Base {
}

class Derived2 extends Base {
}

现在我有了变量 t,它可以是 Derived 或 Derived2 的一个实例。它也可以在运行时多次更改。

/** @type {Base} */
var t = new Derived();
//or
var t = new Derived2();

我有一个函数检查 t 是否是传递类的实例,如果它是传递类的实例则返回 t,否则返回 undefined。

/**
* @template {typeof Base} T
* @param {T} cl
* @returns {T} /// <-- I can't figure out how to return an instance of T
* @returns {instanceof T} /// it's hypothetical, but I need this..
*/
function checkTop( cl ) {
if ( t instanceof cl ) {
return t;
}
return undefined;
}

当我调用 checkTop( Derived ) 时,它的返回类型应该是 Derived。但是对于上面的 jsdoc,它的返回类型是“typeof Derived”。但我想让返回类型只是“派生”。

let d1 = checkTop( Derived ); // 'typeof Derived', but I want 'Derived' as return type

d1 is recognized as 'typeof Derived'

同样,d2 被识别为“typeof Derived2”

let d2 = checkTop( Derived2 ); // 'typeof Derived2'.. but I want 'Derived2' as return type

d2 is recognized as 'typeof Derived2'

如何在 JSDOC 中指定返回类型,以便 checkTop( Derived ); 的返回类型为 Derived,并且 checkTop( Derived2 ) 的返回类型是“Derived2”。

我尝试了以下返回类型:

/**
* @template {Base} B
* @template {typeof B} T
* @param {T} cl
* @returns {B}
*/
function checkTop( cl )

/**
* @template {typeof Base} T
* @param {T} cl
* @returns {instanceof T}
*/
function checkTop( cl )

如果在 JSDOC 中不可能,但在 typescript 中可能,那也会有帮助,但我更喜欢 JSDOC 解决方案。

最佳答案

将模板定义为你需要返回的类型,将参数定义为该类型的构造函数

/**
* @template {Base} T
* @param {new T} cl
* @returns {T}
*/
function checkTop( cl ) {
if ( t instanceof cl ) {
return t;
}
return undefined;
}

结果将是:

function checkTop<T extends Base>(cl: new () => T): T

关于javascript - 在 typescript 中为泛型函数编写 JSdoc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56815302/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com