如何记录 variable/an array/property 包含构造函数?

How to document that a variable/an array/property contains a constructor?

有时,我需要使用字符串或数值来决定构造函数,它们共享相同的class。

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

所以我有一个对象:

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

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

但是我如何证明 servers 包含 ProxyController 基础 class 的构造函数?我需要它才能与 Visual Studio 2017 intellisense 一起使用。

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

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