简体   繁体   English

如何导出模块接口的typedef?

[英]How to export the typedef of a module interface?

Say I have this module foo with the methods bar and baz :假设我有这个模块foo与方法barbaz

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.我想定义返回的 object 的类型,以便可以将其导入到不同的文件中。 But @typedef s can only be imported if they're in the file's outer scope.但是@typedef只有在文件的外部 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.另外,我发现在外部范围内为整个 object 手动编写 typedef 并不是一个好的解决方案,因为文档已经在每种方法中编写过一次。

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.我使用 IDEA 进行开发,我将所有数据类型放在一个单独的文件中,并且我已经向函数指定了数据类型。

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在 function 的代码中,我们指定了返回的数据类型

/**
* @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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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