如何为返回类的WithFeature函数编写JsDoc以支持VSCode智能提示?
解决继承内置类后VSCode智能提示不显示新增方法的JsDoc写法
要让VSCode正确识别通过WithFeature生成的子类(同时继承内置类和拥有feature方法),需要用JsDoc的泛型和类型交集明确类型关系,以下是可行的写法:
完整代码示例
/** * 定义新增的feature方法的类型 * @typedef {Object} FeatureMixin * @property {function(): void} feature - 新增的功能方法 */ /** * 生成继承传入基类并包含feature方法的新类 * @template {new (...args: any[]) => any} T * @param {T} Base - 待扩展的基类构造函数 * @returns {T & {new (...args: ConstructorParameters<T>): InstanceType<T> & FeatureMixin}} */ function WithFeature(Base) { return class extends Base { feature() { console.log('执行feature方法'); } }; } // 继承Array的自定义类 class SomeClass extends Array {} // 继承String的自定义类 class SomeOtherClass extends String {} // 生成带feature的子类 const SomeClassWithFeature = WithFeature(SomeClass); const SomeOtherClassWithFeature = WithFeature(SomeOtherClass); // 测试智能提示 const arrInstance = new SomeClassWithFeature(1, 2, 3); arrInstance.feature(); // VSCode会提示feature方法 arrInstance.push(4); // 保留Array的所有方法提示 const strInstance = new SomeOtherClassWithFeature('hello'); strInstance.feature(); // 提示feature方法 strInstance.slice(1); // 保留String的所有方法提示
关键说明
@typedef定义混入类型:用FeatureMixin明确新增的feature方法的签名,让VSCode识别这个扩展的类型结构。- 泛型
@template约束基类:@template {new (...args: any[]) => any} T指定T是一个构造函数类型,确保传入的Base是可实例化的类。 - 类型交集实现多类型合并:返回值用
T & {new (...args: ConstructorParameters<T>): InstanceType<T> & FeatureMixin},既保留了基类的构造函数特性,又明确实例同时拥有基类实例的所有属性方法和FeatureMixin的方法。
这样就能让VSCode的智能提示同时显示基类(Array/String)的原有方法和新增的feature方法了。
内容的提问来源于stack exchange,提问作者asdru
相关产品推荐
相关产品推荐

