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
1 Answer
Reset to default 14Yes, 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!