简体   繁体   中英

How to export the typedef of a module interface?

Say I have this module foo with the methods bar and baz :

function foo(){
  function bar() {}
  function baz() {}

  return { bar, baz }
}

I want to define the type of the returned object so that I can import it into different files. But @typedef s can only be imported if they're in the file's outer scope.

Here's an approach that 'works' in achieving the desired result but potentially not resilient to certain types of module implementations.

function foo(){
  function bar() {}
  function baz() {}

  return { bar, baz }
}

let type = foo() // Create a arbitrary instance
/** @typedef {type} foo */

Is there an intentional way of defining the type of module interface objects?

Also, I don't find manually writing a typedef for the whole object in the outer-scope a good solution since the documentation is already written once at each method.

I use IDEA for development and I have all the data types in a separate file, and already I specify to the functions what type of data will be.

Perhaps I didn't quite understand your question, but I will indicate the implementation as I see it. It is necessary to describe the data types once, specify once what is returned and everything should work.

Description of types in an external file

/**
* @typedef {Object} barRet
* @property {string} name
* @property {boolean} isOpen
*/

/**
* @typedef {Object} bazRet
* @property {number} openClock
* @property {number} closeClock
*/

/**
* @typedef {Object} fooReturned
* @property {barRet} bars
* @property {bazRet} bazs
*/

In the code for the function, we specify the returned data types

/**
* @returns {fooReturned}
*/
function foo(){
    /** @return {barRet} */
    function bar() {}
    /** @return {bazRet} */
    function baz() {}

    return { bars: bar, bazs: baz }
}

const fooResult = foo(); // I see fooResult type of fooReturned

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