简体   繁体   中英

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

}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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