我看到有些人为这样的 JavaScript 泛型编写 JSDoc(带一个点):
/** @param {Array.<Bar>} bars the bars that should be fooed*/
function foo(bars) {}
Run Code Online (Sandbox Code Playgroud)
和其他类似的(没有点):
/** @param {Array<Bar>} bars the bars that should be fooed*/
function foo(bars) {}
Run Code Online (Sandbox Code Playgroud)
点的重点是什么?哪个版本是正确的?我什么时候应该使用,什么时候不应该?
从语法的角度来看,所有这些类型表达式在运行时都是有效的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;
Run Code Online (Sandbox Code Playgroud)
应该注意的是,Google Closure 编译器似乎无法识别{<type>[]}类型表达式,例如,如果您编译此:
/** @param {string[]} x */
const a = x => x;
Run Code Online (Sandbox Code Playgroud)
您会收到以下警告:
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 */
^
Run Code Online (Sandbox Code Playgroud)
请参阅此 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
Run Code Online (Sandbox Code Playgroud)
所以看起来很像,{Array.<string>}而且{Array<string>}是同一件事。
就我个人而言,我更{Array<string>}倾向于{Array.<string>}. 为什么?点.也是一个“命名空间”分隔符:
/** @namespace */
const Burrito = {};
/** @constructor */
Burrito.beef = function () {};
/** @param {Burrito.beef} x */
const a = x => x;
a("foo");
a(new Burrito.beef());
Run Code Online (Sandbox Code Playgroud)
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");
^
Run Code Online (Sandbox Code Playgroud)
请参阅此 Google Closure Compiler fiddle。
如果{Array<string>}和{Array.<string>}确实是同一件事(我相信这是真的),那么我会更喜欢前者而不是后者,以便保持该字符的含义明确.。
| 归档时间: |
|
| 查看次数: |
177 次 |
| 最近记录: |