JSDoc - Documenting a mixed array

Viewed 4846

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?

1 Answers

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.

Related