如何使用JSDoc标注展开对象合并新属性的函数返回值
场景1:明确知道thingDoer的返回属性,无现成JSDoc可复用
你可以先用@typedef自定义thingDoer的返回类型,再通过&符号实现类型合并,同时注意你的函数返回的是Promise对象,需要标注清楚:
/** * 定义thingDoer的返回值类型 * @typedef {Object} ThingDoerResult * @property {string} name 示例属性,替换为实际属性即可 * @property {number} count 示例属性,替换为实际属性即可 */ /** * it does the things * @param {Object} input 包含id和key的入参对象 * @param {string} input.id 与返回值关联的唯一id * @param {string} input.key 用于获取数据的唯一key * @returns {Promise<ThingDoerResult & {id: string}>} 合并了thingDoer返回属性与id的对象 */ const doTheThings = ({id, key}) => // 注意:直接返回对象字面量需要用小括号包裹,否则会被识别为块级作用域报错 thingDoer(key).then(things => ({ ...things, id }))
这种写法不会额外生成things字段的标注,编辑器会自动识别返回值同时包含ThingDoerResult的所有属性和id属性。
场景2:thingDoer已有可复用的JSDoc注释
你可以直接用JSDoc内置的ReturnType工具类型直接提取thingDoer的返回类型,不需要重复定义属性:
/** * 假设thingDoer已经有现成的JSDoc * @param {string} key 用于获取数据的唯一key * @returns {Promise<{name: string, count: number}>} thingDoer返回的结果 */ const thingDoer = (key) => { // 原有逻辑 } /** * it does the things * @param {Object} input 包含id和key的入参对象 * @param {string} input.id 与返回值关联的唯一id * @param {string} input.key 用于获取数据的唯一key * @returns {Promise<ReturnType<typeof thingDoer> & {id: string}>} 合并了thingDoer返回属性与id的对象 */ const doTheThings = ({id, key}) => thingDoer(key).then(things => ({ ...things, id }))
如果你的JSDoc解析器不支持&合并语法,也可以用最基础的@property逐一枚举所有返回属性:
/** * it does the things * @param {Object} input 包含id和key的入参对象 * @param {string} input.id 与返回值关联的唯一id * @param {string} input.key 用于获取数据的唯一key * @returns {Object} 合并了thingDoer返回属性与id的对象 * @property {string} id 传入的唯一id * @property {string} name 继承自thingDoer的name属性 * @property {number} count 继承自thingDoer的count属性 */
以上所有写法都不需要引入TypeScript,仅靠原生JSDoc即可实现类型提示。
内容的提问来源于stack exchange,提问作者AncientSwordRage
相关产品推荐
相关产品推荐

