Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly set the return type of functions

Tags:

javascript

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?

like image 306
137 Avatar asked Nov 11 '16 17:11

137


People also ask

How do you change the return type of a function?

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.

What is the return type of the function?

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.

How many types of return types are there?

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.

What is return type in TypeScript?

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.


1 Answers

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;
}
like image 138
StriplingWarrior Avatar answered Sep 18 '22 22:09

StriplingWarrior