How can one use @param
to hint the optional param for a function
that is a property (this.selectedPage()
) as well as use @type
to hint its return type?
Take this for example (this.selectedPage()
can receive a page by passing a parameter and return one by passing none):
/**
* @type {function(): Page}
*/
this.selectedPage = ko.observable(data.page);
The type-typehint is nicely picked-up by the IDE and allows for auto-completion of the fact that this.selectedPage()
yields a Page
.
However, please also note that this.selectedPage()
takes a parameter - namely a page. Otherwise the IDE complains that the function allows 0 parameters when trying to pass one.
So I combined the two:
/**
* @type {function(Page): Page}
*/
this.selectedPage = ko.observable(data.page);
This appears to stop the IDE from complaining when trying to pass a parameter, but now it complains when not passing one.
I tried @type {function(undefined|Page): Page}
to no avail.
The function is a getter/setter - so how can one tell the docblock that @param is optional?
Right, after reading-up on the JSDoc specs on various websites, I have now come across Google's Closure Compiler syntax that achieves what I've been trying to do - this is also properly picked-up by IntelliJ/PHPStorm.
Essentially, the optional parameter can be suffixed with =
:
/**
* @type {function(Page=): Page}
*/
this.selectedPage = ko.observable(data.page);
Or a more convoluted example:
/**
* @type {function(Array.<Page>=): Array.<Page>}
*/
this.pages = ko.observableArray();
This does exactly what I want it to: documentation generators and IDEs recognise that the return value of this.selectedPage()
and any items emitted by this.pages()
are, in fact, of the type Page
which, themselves, have all their properties recognised (since the Page
type, too, is documented this way).
Similarly, I believe, this notation should also properly document the (optional) types that can be passed as parameters.