简体   繁体   中英

How to make an wrapper class to copy the JSDoc from a provided function?

I have a wrapper class like this (for a undo-redo system using command pattern):

class Command {
    constructor(doFunction, undoFunction) {
        this.doFunction = doFunction;
        this.undoFunction = undoFunction;
    }

    do = (args) => { return this.doFunction(args) }
    
    undo = (args) => { return this.undoFunction(args) }
}

How can I add JSDoc to the do and undo functions for then use the same @param types from provided this.doFunction and this.undoFunction , so when I use:

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

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

myCommand = new Command(func1, func2)

myCommand.do(...) // Here I want the intellisense to ask me for a `n` @param of type number

I appreciate the help.

You need to type the class, not the functions, because you pass the functions themselves as arguments in the constructor

I would do it like this

/**
 * @typedef {function(arg: number): number} NumberFunc
 */

class Command {
  /**
   * @param {NumberFunc} doFunction
   * @param {NumberFunc} undoFunction
   */
  constructor(doFunction, undoFunction) {
    this.doFunction = doFunction;
    this.undoFunction = undoFunction;
  }
  /** @param {number} args */
  do = (args) => { return this.doFunction(args) }
  /** @param {number} args */
  undo = (args) => { return this.undoFunction(args) }
}

/** @param {number} n */
func1 = (n) => { return n+1 }
/** @param {number} n */
func2 = (n) => { return n-1 }
/** @param {string} n */
func3 = (n) => { return n-1 }

const myCommand = new Command(func1, func2); // ok
const badCommand = new Command(func1, func3); // bad

const myCommand.do(1); // ok
const myCommand.do('1'); // bad

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM