0

有时,我需要使用字符串或数值来决定构造函数,它们都共享同一个类。

例如,现在我正在实现具有多种代理管理模式的反向代理:TCP、UDP 和 symethric UDP。

所以我有一个对象:

const servers = {
    TCP: ProxyControllerTCP,
    UDP: ProxyControllerUDP,
    UDP_sym: UDPProxyBidirectional
};

代理会根据之前的初始化请求选择合适的服务器模块。

但是我如何记录servers包含ProxyController基类的构造函数?我需要它来使用 Visual Studio 2017 智能感知。

4

1 回答 1

0

答案包括两件事,这两件事都很难弄清楚。

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"]并获得基类的类型提示。

于 2018-05-31T15:06:04.763 回答