所以我有一个像这样的基类:
class BaseAPIClass {
/**
* Async factory
* Does some async operation, then instantiates the inheriting class.
*
* @param {String} id
*
* @returns {Promise<???>}
*/
static async create(id) {
const data = await fetchFromNetwork(id)
return new this.prototype.constructor(data)
}
}
还有一个像这样的子类:
class RadAPIClass extends BaseAPIClass {
/**
* Output a compliment.
* @param {name} [name='my dude']
*/
complimentJorts(name = 'my dude') {
const possibleCompliments = ['gnarly', 'tubular', 'bodacious', 'radical', 'sick']
const i = Math.floor(Math.random() * possibleCompliments.length)
const compliment = possibleCompliments[i]
console.log(`Those are some ${compliment} jorts, ${name}!`)
}
}
我的问题是:
如何以正确告诉读者和智能感知
BaseAPIClass.create()
返回RadAPIClass.create()
的方式记录{Promise<RadAPIClass>}
的返回类型?
async function main()
{
const rad = await RadAPIClass.create()
rad.complimentJorts() // I want VSCode to be able to autocomplete this method for me.
}
年纪大了,更聪明了。答案是通用的
@this
。
class BaseAPIClass {
/**
* Async factory
* Does some async operation, then instantiates the inheriting class.
*
* @template {{new(...args: any): any}} T
* @this {T}
*
* @param {String} id
*
* @returns {Promise<InstanceType<T>>}
*/
static async create(id) {
const data = await fetchFromNetwork(id)
return new this.prototype.constructor(data)
}
}
由于
T
,泛型 @this {T}
是从子类的类型推断出来的,因此 Promise<InstanceType<T>>
的返回类型(记住 T
是 typeof BaseAPIClass
或 typeof RadAPIClass
,而不是实例类型)解析为正确的班级。