0

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

??

Normal
  • 1,616
  • 15
  • 39
  • JS Merge objects https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically – Jan Pfeifer Jan 09 '23 at 08:55
  • Does this answer your question? [How can I merge properties of two JavaScript objects dynamically?](https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – Jan Pfeifer Jan 09 '23 at 08:55
  • @JanPfeifer, no guys no, read the question well – Normal Jan 09 '23 at 08:56
  • maybe you are looking for the intersection type: https://stackoverflow.com/questions/36737921/how-to-extend-a-typedef-parameter-in-jsdoc – Diego D Jan 09 '23 at 08:57
  • @DiegoD, I think yes,.. give me a minute – Normal Jan 09 '23 at 08:59

1 Answers1

2

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
}
Normal
  • 1,616
  • 15
  • 39