Vol*_*lox 5 javascript jsdoc typescript visual-studio-code
我使用普通的 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');
}
}
Run Code Online (Sandbox Code Playgroud)
我从 VSCode 得到的结果如下(你可以看到 map 有 type 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');
}
}
Run Code Online (Sandbox Code Playgroud)
shy*_*.me -2
您已secret签名,Map<string, number>;因此secret MUST第一个参数为 as string,第二个参数为number。
正确的例子是
map.set('2',1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
405 次 |
| 最近记录: |