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

如何为命令模式包装类的do/undo方法复用传入函数的JSDoc参数类型?

解决方案:为Command类的do/undo方法复用传入函数的参数类型

可以通过JSDoc的泛型(@template)实现参数类型复用,让IntelliSense自动识别传入函数的参数类型并关联到do和undo方法上。

修改后的Command类(带JSDoc)

/**
 * @template DoArgs, UndoArgs
 * @param {(args: DoArgs) => any} doFunction - 执行命令的函数
 * @param {(args: UndoArgs) => any} undoFunction - 撤销命令的函数
 */
class Command {
    constructor(doFunction, undoFunction) {
        this.doFunction = doFunction;
        this.undoFunction = undoFunction;
    }

    /**
     * 执行命令
     * @param {DoArgs} args - 复用doFunction的参数类型
     * @returns {ReturnType<typeof this.doFunction>} - 自动推导doFunction的返回值类型
     */
    do = (args) => { return this.doFunction(args) }
    
    /**
     * 撤销命令
     * @param {UndoArgs} args - 复用undoFunction的参数类型
     * @returns {ReturnType<typeof this.undoFunction>} - 自动推导undoFunction的返回值类型
     */
    undo = (args) => { return this.undoFunction(args) }
}

使用示例

/** @param {number} n */
const func1 = (n) => { return n+1 }

/** @param {number} n */
const func2 = (n) => { return n-1 }

const myCommand = new Command(func1, func2)

myCommand.do(...) // IntelliSense会提示需要传入number类型的参数n
myCommand.undo(...) // 同样会提示需要传入number类型的参数n

支持不同参数类型的场景

如果do和undo需要不同的参数类型,这个方案也能完美适配:

/** @param {string} str */
const doUpperCase = (str) => { return str.toUpperCase() }

/** @param {number} step */
const undoStep = (step) => { return step - 1 }

const mixedCommand = new Command(doUpperCase, undoStep)
mixedCommand.do("hello") // 提示传入string类型参数
mixedCommand.undo(3) // 提示传入number类型参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:05:22