显式设置函数的返回类型

Dus*_* E. 3 javascript

我最近在讨论JS代码,我找到了以下注释:

/**
* Explicitly set the return type here to prevent the primitive being lost when using new
* @return {boolean}
*/
function giveMeABoolean(please) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

是什么赋予了?JS中的返回类型?我一直在网上闲逛,找不到任何相关信息.经过一些测试后,在没有注释的情况下使用new时,原语确实会丢失 .谁能解释这个注释是如何工作的?

Str*_*ior 6

这些评论是JSDoc,这是一种可以记录代码的方法.像IDE这样的工具可以获取这些文档,并在您尝试理解方法的API时以良好的格式向您显示.

当他们进行静态分析时,某些工具也可能包含这些信息,以帮助您提供智能感知等提示.这将给开发人员留下这样的印象:返回值的"类型"在他们使用代码时被保留/知道.但是,这些注释在运行时不会产生任何影响.

这是@return评论的文档.这里有一个相关的例子:

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)


ska*_*kav 5

我认为该代码的作者正在为文档目的提供该信息。如果您真的想提供类型信息,您可以考虑打字稿流程