Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSDoc: declare @type for variable in "for...of" loop

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) {

}
like image 690
Alex Gusev Avatar asked Jul 13 '17 05:07

Alex Gusev


1 Answers

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!

like image 86
Lucio Paiva Avatar answered Sep 28 '22 23:09

Lucio Paiva