如何在 JSDOC 中扩展一个typedef的参数?

huangapple go评论69阅读模式
英文:

How to extend a typedef parameters in JSDOC?

问题

/**
 * @typedef {Object} obj1
 * @property {boolean} a - Property 1
 * @property {boolean} b - Property 2
 */

/**
 * @typedef {obj1} obj2
 * @property {boolean} c - Property 3
 * @property {boolean} d - Property 4
 */
英文:

I have a JSDoc comment of a typedef like below,

/**
 * @typedef {Object} obj1
 * @property {boolean} a - Property 1
 * @property {boolean} b - Property 2
 */

I want to have a new typedef which includes the following properties as well:

* @property {boolean} c - Property 3
* @property {boolean} d - Property 4

How to add any additional properties to the object besides a and b?

In code, it's like this:

const obj1 = {
  a: true,
  b: false
}

const obj2 = {
  a: true,
  b: false,
  c: true,
  d: false
}

As you can see a and b are shared, so I don't want to repeat defining them, they're exactly the same.

How to add properties to an existing definition?

in code, we can do something like:

const obj2 = {
  ...obj1,
  c: true,
  d: false
}

Can we do something like the following jsDoc?

/**
 * @typedef {Object} obj1
 * @property {boolean} a - Property 1
 * @property {boolean} b - Property 2
 */

/**
 * @typedef {Object} obj2
 * @property {...obj1}
 * @property {boolean} c - Property 3
 * @property {boolean} d - Property 4
 */

??

答案1

得分: 2

解决方案很简单:

通过使用以下语法:

/** 
 * @typedef {Obj1Props & Obj2Props} obj2
*/

完整的解决方案:

/**
 * @typedef {Object} Obj1Props
 * @property {boolean} a - 属性1
 * @property {boolean} b - 属性2
 */

/**
 * @typedef {Object} Obj2Props
 * @property {boolean} c - 属性3
 * @property {boolean} d - 属性4
 */

/** 
 * @typedef {Obj1Props & Obj2Props} obj2
*/

/** @type {Obj1Props} */
const obj1 = {
  a: true,
  b: false
}

/** @type {obj2} */
const obj2 = {
  a: true,
  b: false,
  c: true,
  d: false
}
英文:

The solution is simple:

it's by using this syntax:

/** 
 * @typedef {Obj1Props & Obj2Props} obj2
*/

Full solution:

/**
 * @typedef {Object} Obj1Props
 * @property {boolean} a - Property 1
 * @property {boolean} b - Property 2
 */

/**
 * @typedef {Object} Obj2Props
 * @property {boolean} c - Property 3
 * @property {boolean} d - Property 4
 */

/** 
 * @typedef {Obj1Props & Obj2Props} obj2
*/

/** @type {Obj1Props} */
const obj1 = {
  a: true,
  b: false
}

/** @type {obj2} */
const obj2 = {
  a: true,
  b: false,
  c: true,
  d: false
}

huangapple
  • 本文由 发表于 2023年1月9日 16:53:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054943.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定