Normal
Normal

Reputation: 3596

How to extend a typedef parameters in JSDOC?

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
 */

??

Upvotes: 3

Views: 1825

Answers (1)

Normal
Normal

Reputation: 3596

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
}

Upvotes: 6

Related Questions