12

In JSDoc, how to document an array accepting multiple object class like this:

var arr = [new Foo(), new Bar()];

How to write the type such that Foo and Bar are the only class that are accepted in the array?

4
  • Is this the correct way? /** @type {[Foo|Bar]} */ Commented Mar 25, 2016 at 17:27
  • 3
    I believe that you are looking for {Array.<Foo|Bar>} Commented Mar 25, 2016 at 17:33
  • 2
    Another option is {(Foo|Bar)[]} Commented May 16, 2019 at 15:34
  • @KevinLaw [Foo|Bar] would mean a one element tuple where the first/only element is Foo or Bar. Commented Dec 3, 2021 at 7:58

1 Answer 1

15

If the type of the first object should always be Foo and the second always Bar, we're looking at what would be understood as a tuple object. In this case, the correct JSDoc type would be:

/** @type {[Foo, Bar]} */
const arr = [new Foo(), new Bar()];

And not Array<Foo|Bar> as one could've thought, since the latter allows for things like [new Foo(), new Foo()], which is probably undesired.

Sign up to request clarification or add additional context in comments.

5 Comments

in jsdoc 3.6.3 (and I assume all earlier versions), this syntax is illegal and throws an error
Is there any official documentation about this JSDoc notation? See github.com/gajus/eslint-plugin-jsdoc/issues/…
I am afraid that [Foo, Bar] is used for tuples. I.e. a tuple with exactly two elements where the first one is Foo and the second Bar. A general array that can have multiple Foos and Bars will be (Foo|Bar)[] as @austin_ce suggested.
You are correct, @dannymo. If you read my answer carefully, you'll see that it presupposes a tuple with predetermined types for each position. For an array where types can be at any position, austin_ce's suggestion is correct indeed.
Its 2022 and this syntax is still illegal. Whilst vscode can handle this syntax, the jsdoc CLI cannot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.