英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论