admin管理员组

文章数量:1243256

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?

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?

Share Improve this question edited Apr 20, 2020 at 11:49 Yves M. 31k24 gold badges109 silver badges149 bronze badges asked Mar 25, 2016 at 17:21 Kevin LawKevin Law 4,0802 gold badges28 silver badges20 bronze badges 4
  • Is this the correct way? /** @type {[Foo|Bar]} */ – Kevin Law Commented Mar 25, 2016 at 17:27
  • 3 I believe that you are looking for {Array.<Foo|Bar>} – Pandawan Commented Mar 25, 2016 at 17:33
  • 2 Another option is {(Foo|Bar)[]} – austin_ce 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. – dannymo Commented Dec 3, 2021 at 7:58
Add a ment  | 

1 Answer 1

Reset to default 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.

本文标签: javascriptJSDocDocumenting a mixed arrayStack Overflow