答案包括两件事,这两件事都很难弄清楚。
1. 记录对象的值类型
这是记录 object 包含哪些值的语法:
/** @type {[key: string]: number} **/
const myObjOfNumbers = {};
// Visual studio hints number type, even though the value is not defined right now
const num = myObjOfNumbers["hello world"];
2.定义构造函数类型
这更直观:
/** @type {new HTMLElement} **/
const test = null;
// Visual studio hints HTMLElement type, even though HTMLElement does not
// have a public constructor
const elm = new test();
结合你的力量:
/** @type {{[x:string]: new ProxyController}} **/
const servers = {
TCP: ProxyControllerTCP,
UDP: ProxyControllerUDP,
UDP_sym: UDPProxyBidirectional
};
我现在可以使用new servers["UDP"]并获得基类的类型提示。