You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JSDoc正确标注函数返回另一函数调用的结果?

解决JSDoc标注问题,实现another().brand直接访问

问题根源

你之前的@returns {carModel}标注错误地将another的返回类型指定为carModel函数本身,但实际上another返回的是carModel()调用后的对象实例,不是函数。这就是为什么编辑器要求你写another()().brand——它以为another()返回的是个函数,需要再执行一次才能拿到对象。

几种正确的标注方案

方案1:先定义对象类型再引用

先给carModel返回的对象定义一个可复用的类型,再在两个函数的返回值里引用:

/**
 * @typedef {Object} Car
 * @property {string} brand - 汽车品牌
 * @property {string} model - 车型
 */

/**
 * @returns {Car}
 */
function carModel() {
    return {
        brand: "NIO",
        model: "ET5"
    }
}

/**
 * @returns {Car}
 */
function another() {
    // 不可预测的代码,最终返回carModel()的结果
    return carModel();
}

方案2:用ReturnType直接复用carModel的返回类型

如果你的编辑器支持TypeScript语法(比如VS Code),可以不用额外定义类型,直接通过ReturnType获取carModel的返回类型:

function carModel() {
    return {
        brand: "NIO",
        model: "ET5"
    }
}

/**
 * @returns {ReturnType<typeof carModel>}
 */
function another() {
    // 不可预测的代码,最终返回carModel()的结果
    return carModel();
}

方案3:直接在返回值里描述对象结构

如果不需要复用类型,可以直接在@returns里写出对象的结构:

function carModel() {
    return {
        brand: "NIO",
        model: "ET5"
    }
}

/**
 * @returns {{brand: string, model: string}}
 */
function another() {
    // 不可预测的代码,最终返回carModel()的结果
    return carModel();
}

效果

用以上任意一种方式标注后,编辑器就能识别another()返回的是包含brand和model属性的对象,你可以直接通过another().brand访问属性。

内容的提问来源于stack exchange,提问作者Khanif Ikhsanudin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 12:51:15