【问题标题】:When should there be a dot in JSDoc generics?JSDoc 泛型中什么时候应该有一个点?
【发布时间】:2021-01-07 03:06:58
【问题描述】:

我看到有些人为这样的 JavaScript 泛型编写 JSDoc(带点):

/** @param {Array.<Bar>} bars the bars that should be fooed*/
function foo(bars) {}

和其他类似的(不带点):

/** @param {Array<Bar>} bars the bars that should be fooed*/
function foo(bars) {}

点的意义是什么?哪个版本是正确的?什么时候应该使用,什么时候不应该?

【问题讨论】:

标签: javascript jsdoc


【解决方案1】:

从语法的角度来看,当您运行 jsdoc index.js 时,所有这些类型的表达式都是有效的

/** @param {Array} x */
const a = x => x;

/** @param {Array.<string>} x */
const b = x => x;

/** @param {Array<string>} x */
const c = x => x;

/** @param {string[]} x */
const d = x => x;

应该注意的是,Google Closure Compiler 似乎无法识别 {&lt;type&gt;[]} 类型表达式,例如如果你编译这个:

/** @param {string[]} x */
const a = x => x;

您会收到以下警告:

JSC_TYPE_PARSE_ERROR: Bad type annotation. expected closing } See https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler for more information. at line 1 character 18
/** @param {string[]} x */
                  ^
JSC_TYPE_PARSE_ERROR: Bad type annotation. expecting a variable name in a @param tag. See https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler for more information. at line 1 character 18
/** @param {string[]} x */
                  ^

请参阅此 Google Closure Compiler fiddle

VS Code 中的静态类型检查器会报错最后三个函数调用:

// @ts-check

/** @param {Array} x */
const a = x => x;

/** @param {Array.<string>} x */
const b = x => x;

/** @param {Array<string>} x */
const c = x => x;

/** @param {string[]} x */
const d = x => x;

a(['foo', 3]); // OK (we just need an array)
b(['foo', 3]); // ERR: 3 is not a string
c(['foo', 3]); // ERR: 3 is not a string
d(['foo', 3]); // ERR: 3 is not a string

所以看起来{Array.&lt;string&gt;}{Array&lt;string&gt;} 是同一个东西。

我个人更喜欢{Array&lt;string&gt;} 而不是{Array.&lt;string&gt;}。为什么?点. 也是“命名空间”分隔符:

/** @namespace */
const Burrito = {};

/** @constructor */
Burrito.beef = function () {};

/** @param {Burrito.beef} x */
const a = x => x;

a("foo");
a(new Burrito.beef());

Google Closure 编译器会发出关于第一次调用的警告(第二次调用没问题):

JSC_TYPE_MISMATCH: actual parameter 1 of a does not match formal parameter
found   : string
required: (Burrito.beef|null) at line 10 character 2
a("foo");
  ^

请参阅此 Google Closure Compiler fiddle

如果{Array&lt;string&gt;}{Array.&lt;string&gt;} 真的是同一件事(我相信这是真的),那么我会更喜欢前者而不是后者,以保持. 字符的含义明确。

【讨论】:

    【解决方案2】:

    根据 JSDoc 文档,带点的语法是正确的。 https://jsdoc.app/tags-type.html

    MyClass 实例的数组。

    {Array.<MyClass>}
    // or:
    {MyClass[]}
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多