从javascript生成打字稿声明文件 [英] Generating typescript declaration files from javascript
问题描述
比如说,你有一个 npm 库,在我的例子中是 mongoose
,你会如何生成 d.ts
文件?
Say for example, you have a npm library, in my case mongoose
, how would you go about generating d.ts
files?
推荐答案
JavaScript 并不总是包含足够的类型信息供 TypeScript 编译器推断代码中的结构 - 因此基于 JavaScript 自动生成定义很少是一种选择.
JavaScript doesn't always contain enough type information for the TypeScript compiler to infer the structures in your code - so automatically generating a definition based on JavaScript is rarely an option.
这里有关于如何从头开始编写它们的说明:
There are instructions on how to write them from scratch here:
https://www.stevefenton.co.uk/2013/01/complex-typescript-definitions-made-easy/
但是有一个技巧可能会奏效(它只在有限的情况下有效).
But there is one trick that might work (it only works in a limited set of cases).
如果您将 JavaScript 粘贴到新的 TypeScript 文件中,修复您可能遇到的任何小错误并使用定义标志编译它,它可能会为您提供一个至少可以作为起点的文件.
If you paste the JavaScript into a new TypeScript file, fix any trivial errors you may get and compile it using the definition flag, it may be able to get you a file that would at least be a starting point.
tsc --declaration js.ts
这篇关于从javascript生成打字稿声明文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!