如果我将TypeScript模块保存为my-function.ts,如下所示:
export function myFunction (param: number): number { return param }
这将以任何方式编译成JavaScript,并释放其类型定义。然后,我能够创建一个index.d.ts文件来声明此模块的定义,但重新定义/重新声明定义似乎有点乏味。
是否有方法从my-function.ts文件自动生成类型定义到index.d.ts文件?
如果我将TypeScript模块保存为my-function.ts,如下所示:
export function myFunction (param: number): number { return param }
这将以任何方式编译成JavaScript,并释放其类型定义。然后,我能够创建一个index.d.ts文件来声明此模块的定义,但重新定义/重新声明定义似乎有点乏味。
是否有方法从my-function.ts文件自动生成类型定义到index.d.ts文件?
2条答案
按热度按时间yyhrrdl81#
如果使用
--declaration
标志进行编译,TypeScript将自动为您生成.d.ts
文件。此模式将要求某些类型可见,以便可以在
.d.ts
文件中描述它们。pcww981p2#
以下是我解决问题的方法:
创建基础结构
1.使用infra的typescript创建新的节点程序包。
1.在新包中,确保使用声明:true配置tsconfig.json。这样做将导致typescript生成可供此基础结构的用户使用的定义文件。
我的tsconfig.json:
1.创建一个**“index.ts”**文件,该文件将导出基础架构的公共API。
注意:为了能够转换和创建对象的示例,每个实体需要两个不同的导出。一个导出为type,另一个导出为const。
这是我的索引
你可以在这里阅读更多关于这个双重声明背后的推理的信息:https://github.com/Microsoft/TypeScript/issues/10058#issuecomment-236458961
1.完成以下所有操作后,当我们运行build时,我们应该有每种类型对应的“.d.ts”文件。现在我们必须处理infra的 package.json,以便打包所有项。
1.在 package.json 中,确保将 types、main 设置为指向生成的 index.d.ts 和 index.js 文件。此外,还必须确保“.d.ts”文件被打包为infra的一部分。在我的示例中,我在 files 属性中指定了以下模式:“ts输出/**/*.d.ts”
"这是我的包裹“
全部完成。现在您可以发布您的公用代码了。
使用代码
1.安装infra。在本例中,用户必须用途:
npm install my-js-infra --save
1.修改使用应用程序的tsconfig.json,以使用Node模块解析来载入模块。您可以在档案中设定moduleResolution:true来执行此动作。
这是我的tsconfig.json:
有关Typescript中的模块解析的详细信息,请参阅此处:https://www.typescriptlang.org/docs/handbook/module-resolution.html
1.开始使用代码。例如: