我使用纯 Javascript 创建类并使用 JSDoc 记录它,我使用 typescript 进行类型检查。
但我不知道如何正确编写 JSDoc,以便它可以识别使用符号的字段访问。
const secret = Symbol('secret');
class MyClass {
constructor() {
/** @type {Map<string,number>} */
this[secret] = new Map();
}
method() {
const map = this[secret];
// Should give an error in the following line since 1 is not a string
map.set(1, '2');
}
}
我从 VSCode 得到的结果如下(如您所见, map 的类型为 any
):
在 TypeScript 中很容易让它工作,只需像任何其他类属性一样声明它。
const secret = Symbol('secret');
class MyClass {
[secret]: Map<string, number>; // Declared here
constructor() {
this[secret] = new Map();
}
method() {
const map = this[secret];
map.set(1, '2');
}
}
最佳答案
你已经 secret
签名为 Map<string, number>;
所以secret
MUST
第一个参数为 string
第二个参数为 number
.
正确的例子是
map.set('2',1)
关于javascript - 如何使用 JSDoc 记录符号索引签名以符合 typescript ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50909908/