如何让VSCode/JSDoc识别匿名类构造器中this.constructor的静态成员类型?
JavaScript匿名类中
this.constructor静态方法的类型识别问题 一、自动识别this.constructor.coords()的类型
在构造器中,VSCode的类型推断默认无法精准识别this.constructor的具体类型,导致调用静态方法返回any。可以通过JSDoc标注this.constructor的类型解决,无需手动转换返回值:
方法1:直接标注构造器类型
利用typeof操作符获取类的构造函数类型,添加JSDoc标注:
MyAnonymousClass = class { static coords(){ return [{x:0, y:1}, {x:1, y:0}, {x:-1, y:-1}]; } constructor(){ /** @type {typeof MyAnonymousClass} */ const cls = this.constructor; const x = cls.coords(); // 此时x的类型会被正确识别为 {x: number; y: number;}[] } } AnotherAnonymousClass = class extends MyAnonymousClass{ static coords(){ return [{x:0, y:2}, {x:-2, y:0}]; } }
这种方式能自动继承子类的静态方法类型,比如AnotherAnonymousClass实例调用时,x的类型会对应子类coords的返回值。
方法2:用@typedef定义静态契约(完全匿名场景)
如果不想给类命名,可先通过@typedef定义静态方法的类型契约,再标注this.constructor:
/** * @typedef {{ * coords: () => {x: number; y: number;}[] * }} CoordsStatic */ const MyAnonymousClass = class { static coords(){ return [{x:0, y:1}, {x:1, y:0}, {x:-1, y:-1}]; } constructor(){ /** @type {CoordsStatic} */ const cls = this.constructor; const x = cls.coords(); // x类型正确识别为目标数组类型 } }
二、给this.cls = this.constructor添加匿名类类型
通过JSDoc标注即可实现,无需给类命名:
/** * @typedef {{ * coords: () => {x: number; y: number;}[] * }} CoordsStatic */ const MyAnonymousClass = class { static coords(){ return [{x:0, y:1}, {x:1, y:0}, {x:-1, y:-1}]; } constructor(){ /** @type {CoordsStatic} */ this.cls = this.constructor; // 后续调用this.cls.coords()时,返回类型会被正确识别 } }
如果需要保留类的实例类型关联,也可以用typeof this.constructor结合类的自引用:
const MyAnonymousClass = class { static coords(){ return [{x:0, y:1}, {x:1, y:0}, {x:-1, y:-1}]; } constructor(){ /** @type {typeof MyAnonymousClass} */ this.cls = this.constructor; // this.cls既包含静态方法,也能关联类的构造函数类型 } }
内容的提问来源于stack exchange,提问作者Carlos Pinzón
相关产品推荐
相关产品推荐

