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.
P.S.: notice I declared one
as const
. Despite of what one may guess, you can declare for..of
loop variables as constants!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With