woo*_*hoh 10 javascript jsdoc visual-studio-code
I've distilled an essence of my problem with following codes:
I have Base class, and Derived, Derived2:
class Base {
static get type() {
return 'Base';
}
}
class Derived extends Base {
}
class Derived2 extends Base {
}
Run Code Online (Sandbox Code Playgroud)
Now I have variable t, which could be an instance of Derived or Derived2. It can also be changed multiple times during runtime.
/** @type {Base} */
var t = new Derived();
//or
var t = new Derived2();
Run Code Online (Sandbox Code Playgroud)
我有一个函数检查t是否是已传递类的实例,如果它是已传递类的实例或未定义,则返回t。
/**
* @template {typeof Base} T
* @param {T} cl
* @returns {T} /// <-- I can't figure out how o return an instance of T
*/
function checkTop( cl ) {
if ( t instanceof cl ) {
return t;
}
return undefined;
}
Run Code Online (Sandbox Code Playgroud)
当我调用checkTop(Derived)时,其返回类型应该为Derived。但是在上面的jsdoc中,其返回类型为'typeof Derived'。但我想将返回类型设为“派生”。
let d1 = checkTop( Derived ); // 'typeof Derived', but I want 'Derived' as return type
Run Code Online (Sandbox Code Playgroud)
同样,d2被识别为“ typeof Derived2”
let d2 = checkTop( Derived2 ); // 'typeof Derived2'.. but I want 'Derived2' as return type
Run Code Online (Sandbox Code Playgroud)
如何在JSDOC中指定返回类型,以使checkTop( Derived );返回类型为Derived,而checkTop( Derived2 )返回类型为'Derived2'。
我尝试以下返回类型:
/**
* @template {Base} B
* @template {typeof B} T
* @param {T} cl
* @returns {B}
*/
function checkTop( cl )
Run Code Online (Sandbox Code Playgroud)
和
/**
* @template {typeof Base} T
* @param {T} cl
* @returns {instanceof T}
*/
function checkTop( cl )
Run Code Online (Sandbox Code Playgroud)
如果在JSDOC中是不可能的,但在打字稿中是不可能的,那也将有所帮助,但我更喜欢JSDOC解决方案。
将模板定义为您需要返回的类型,并将参数定义为该类型的构造函数
/**
* @template {Base} T
* @param {new T} cl
* @returns {T}
*/
function checkTop( cl ) {
if ( t instanceof cl ) {
return t;
}
return undefined;
}Run Code Online (Sandbox Code Playgroud)
结果将是:
function checkTop<T extends Base>(cl: new () => T): T
Run Code Online (Sandbox Code Playgroud)