如何在 JSDoc 中正确定义自己的 class 类型?
How to properly define own type of class in JSDoc?
我有一个简单的 ES6 class,我想知道如何在 JSDoc 中正确描述它。请注意,我想定义我自己的类型,稍后将被 WebStorm 自动完成识别。
下面的例子有效吗?
/**
* @typedef {Object} View
* @class
*/
class View{...}
这真是个好问题。我今天的做法是在其构造函数中声明我所有的 class 实例变量,并用其预期类型注释每个实例变量。这是一个很好的做法,并且与 Webstorm 配合得很好。例如:
class MyClass {
constructor () {
/** @type {Number} some number value */
this.someNumber = 0;
/** @type {String} some relevant string */
this.someString = null;
/** @type {Map<Number, Set<String>>} map numbers to sets of strings */
this.strSetByNumber = new Map();
}
/**
* Some sample function.
*
* @param {Number} a - first value
* @param {Number} b - second value
* @return {Number} the resulting operation
*/
someFunction(a, b) {
return a + b;
}
}
现在只需将一些变量声明为 MyClass
类型并享受自动完成:
如果您尝试为某些属性分配错误的类型:
然而,有时您甚至不需要声明 class。例如,您希望通过 JSON 接收到一个对象,并且您需要对其进行一些处理。您可以使用纯 JSDoc 来帮助检查您的代码,而无需声明 class。假设您期待这样的 JSON:
{
"foo": "bar",
"fizz": 42
}
不要声明 class,而是在代码中的某个地方执行此操作(我更喜欢将它始终放在将要使用它的脚本的顶部):
/**
* @typedef {Object} MyType
* @property {String} foo - this is some cool string
* @property {Number} fizz - some number we also expect to receive
* @property {Number} [bar] - an optional property
*/
就是这样!亲自尝试一下,看看 Webstorm 如何能够很好地理解这两种方法。
我有一个简单的 ES6 class,我想知道如何在 JSDoc 中正确描述它。请注意,我想定义我自己的类型,稍后将被 WebStorm 自动完成识别。
下面的例子有效吗?
/**
* @typedef {Object} View
* @class
*/
class View{...}
这真是个好问题。我今天的做法是在其构造函数中声明我所有的 class 实例变量,并用其预期类型注释每个实例变量。这是一个很好的做法,并且与 Webstorm 配合得很好。例如:
class MyClass {
constructor () {
/** @type {Number} some number value */
this.someNumber = 0;
/** @type {String} some relevant string */
this.someString = null;
/** @type {Map<Number, Set<String>>} map numbers to sets of strings */
this.strSetByNumber = new Map();
}
/**
* Some sample function.
*
* @param {Number} a - first value
* @param {Number} b - second value
* @return {Number} the resulting operation
*/
someFunction(a, b) {
return a + b;
}
}
现在只需将一些变量声明为 MyClass
类型并享受自动完成:
如果您尝试为某些属性分配错误的类型:
然而,有时您甚至不需要声明 class。例如,您希望通过 JSON 接收到一个对象,并且您需要对其进行一些处理。您可以使用纯 JSDoc 来帮助检查您的代码,而无需声明 class。假设您期待这样的 JSON:
{
"foo": "bar",
"fizz": 42
}
不要声明 class,而是在代码中的某个地方执行此操作(我更喜欢将它始终放在将要使用它的脚本的顶部):
/**
* @typedef {Object} MyType
* @property {String} foo - this is some cool string
* @property {Number} fizz - some number we also expect to receive
* @property {Number} [bar] - an optional property
*/
就是这样!亲自尝试一下,看看 Webstorm 如何能够很好地理解这两种方法。