最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSDoc: declare @type for variable in "for...of" loop - Stack Overflow

programmeradmin3浏览0评论

Can I declare type for variable one using JSDoc @type annotation?

/** @type some.type */
for (let one of many) {
    ...
}

Something like PHPDoc annotation:

/** @var \Some\Type $one */
foreach ($many as $one) {

}

Can I declare type for variable one using JSDoc @type annotation?

/** @type some.type */
for (let one of many) {
    ...
}

Something like PHPDoc annotation:

/** @var \Some\Type $one */
foreach ($many as $one) {

}
Share Improve this question edited Jul 13, 2017 at 7:33 Alex Gusev asked Jul 13, 2017 at 5:20 Alex GusevAlex Gusev 1,8543 gold badges21 silver badges41 bronze badges 2
  • I don't think I'd normally expect type declarations inside a function. Wouldn't you look at the documentation for whatever created many? – loganfsmyth Commented Jul 13, 2017 at 5:31
  • 1 @loganfsmyth , I use PHPDoc @var annotations in any place of my code to annotate the type of any variable. Can I do the same with JSDoc? – Alex Gusev Commented Jul 13, 2017 at 7:46
Add a ment  | 

1 Answer 1

Reset to default 14

Yes, you can. You just have to move the type declaration inside of the parentheses, before your variable:

for (/** @type {SomeType} */ const one of many) {
    // ...
}

This works just fine, although I usually prefer specifying the type of many instead. For instance:

/** @type {Number[]} */
const many = [1, 2, 3, 4];

And then the type of one will be automatically inferred.

P.S.: notice I declared one as const. Despite of what one may guess, you can declare for..of loop variables as constants!

发布评论

评论列表(0)

  1. 暂无评论