简体   繁体   English

如何使用 JSDoc 记录符号索引签名以符合打字稿?

[英]How to document symbol index signature using JSDoc to be typescript compliant?

I am using plain Javascript for creating a class and documenting it using JSDoc and I am using typescript for type checking.我使用普通的 Javascript 来创建一个类并使用 JSDoc 记录它,我使用 typescript 进行类型检查。

But I cannot figure out how to write a JSDoc properly so it would recognise the field access using a Symbol.但是我无法弄清楚如何正确编写 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');
  }
}

The result I get from VSCode is the following (as you can see map has type any ):我从 VSCode 得到的结果如下(你可以看到 map 的类型是any ): VSCode 结果

In TypeScript is pretty easy to make it work, just declare it like any other class property.在 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');
  }
}

The VSCode (typescript) error i get:我得到的 VSCode(打字稿)错误: VSCode 错误

You've secret signature as Map<string, number>;你的secret签名是Map<string, number>; so secret MUST have first param as string and second param as number .所以secret MUST将第一个参数作为string ,第二个参数作为number

Correct example would be正确的例子是

map.set('2',1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM