Reputation: 831
I recently was poking around JS code and I found the following annotation:
/**
* Explicitly set the return type here to prevent the primitive being lost when using new
* @return {boolean}
*/
function giveMeABoolean(please) {
...
}
What gives? Return types in JS? I've been poking around online and can't find anything about this. After some testing the primitive is indeed lost when using new without the annotation. Can anyone explain how this annotation works?
Upvotes: 18
Views: 25572
Reputation: 156624
Those comments are JSDoc, which is just a way you can document your code. Tools like IDEs can pick up on this documentation and show it to you with nice formatting when you are trying to understand the API for a method.
It's also likely that some tools include this information when they do static analysis to help give you hints for things like intellisense. That would give developers the impression that the "type" of the returned value is preserved/known while they're working with the code. However, these comments will have no impact at runtime.
Here's the documentation for the @return comment. And here's a relevant example that's provided there:
/**
* Returns the sum of a and b
* @param {Number} a
* @param {Number} b
* @param {Boolean} retArr If set to true, the function will return an array
* @returns {Number|Array} Sum of a and b or an array that contains a, b and the sum of a and b.
*/
function sum(a, b, retArr) {
if (retArr) {
return [a, b, a + b];
}
return a + b;
}
Upvotes: 26
Reputation: 1460
I think the author of that code is providing that information for documentation purposes. If you really wanted to provide type information you might consider typescript or flow
Upvotes: 6