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?
To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.
The result of a function is called its return value and the data type of the return value is called the return type. Every function declaration and definition must specify a return type, whether or not it actually returns a value.
A return type may be a primitive type like int, float, double, a reference type or void type(returns nothing). The type of data returned by a method must be compatible with the return type specified by the method.
The ReturnType in TypeScript is a utility type which is quite similar to the Parameters Type. It let's you take the return output of a function, and construct a type based off it.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With