我使用普通的Javascript创建一个类并使用JSDoc记录它,我使用typescript进行类型检查 .
但我无法弄清楚如何正确编写JSDoc,因此它会识别使用Symbol的字段访问 .
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');
}
}
我得到的VSCode(打字稿)错误:
1 回答
请参见图1,默认情况下不会显示错误,您必须输入
// @ts-check
才能启用错误 . 但是如果你看到图像2,Map
的类型显示any,any
,所以它不起作用 .