有时,我需要使用字符串或数值来决定构造函数,它们都共享同一个类。
例如,现在我正在实现具有多种代理管理模式的反向代理:TCP,UDP和对称UDP。
所以我有一个对象:
const servers = {
TCP: ProxyControllerTCP,
UDP: ProxyControllerUDP,
UDP_sym: UDPProxyBidirectional
};
代理将根据先前的初始化请求选择正确的服务器模块。
但是,如何记录包含ProxyController
基类的构造函数的servers
呢?我需要它来与Visual Studio 2017智能感知一起工作。
答案包括两件事,两者都很难弄清楚。
1. 记录对象的值类型
这是记录对象包含哪些值的语法:
/** @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"]
并获取基类的类型提示。