How to generate a d.ts from a .js file

Topics: General
Jul 31, 2013 at 3:32 PM
In Issue 1401 I asked If is correct to try to generate the .d.ts from any .js file and the answer that RyanCavanaugh gave is that this is not a supported scenario.


Considering that any javascript file can be compiled as one typescript file, what is the fastest way to create a d.ts file from a javascript?

I know it's not typed, but after this first creation I'll type the d.ts file.
Coordinator
Aug 1, 2013 at 3:00 PM
By renaming .js to .ts and compiling with --declaration. I believe that if your .js files are valid, what comes out of a compile after doing a rename to .ts should also be a valid .d.ts file. You may have to fix up a couple type errors, but other than that it should work.
Aug 5, 2013 at 10:40 PM
Why I can't generate the declaration file from http://mathjs.org/js/lib/math.js.

I downloaded the latest version of typescript, downloaded this lib, renamed it to .ts but when I try to generate, the js file is generated, i used this command

tsc --declaration math.ts
Coordinator
Aug 6, 2013 at 2:47 PM
I should have stressed earlier that you would have to fix up the type errors. You won't be able to just rename .js and get useful .d.ts out. If you could, in all honesty, we wouldn't need TypeScript. The compiler can't infer all the types accurately, so when you're converting JS over, you're going to have to give that information. In some cases, there will be relatively few such type errors to fix. Other times, there are a lot more. It's just based on the style the JS is written in.

In looking at math.js, I can see that it used a lot of expando style JS. For example, towards the bottom there are a log of math.docs.xxx = ??? lines. You would need to supply the type information for these in the current version of TypeScript (in the future, we may do more to help infer these patterns better).

The short of it is that almost all .d.ts files are written by hand because you are the one with the best understanding of what the API should be. The compiler can take a guess, but it's meant to work with type information, and you'll need to supply that where it's needed.