Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating typescript declaration files from javascript

Tags:

typescript

Say for example, you have a npm library, in my case mongoose, how would you go about generating d.ts files?

like image 296
Games Brainiac Avatar asked Aug 18 '13 17:08

Games Brainiac


People also ask

Which command is used to generate a JavaScript file from a TypeScript file?

When we execute tsc filename. ts , TypeScript will generate a js file with the same name at runtime.

What Is A TypeScript declaration file?

Declaration files, if you're not familiar, are just files that describe the shape of an existing JavaScript codebase to TypeScript. By using declaration files (also called . d. ts files), you can avoid misusing libraries and get things like completions in your editor.

What is D ts file in TypeScript?

The "d. ts" file is used to provide typescript type information about an API that's written in JavaScript. The idea is that you're using something like jQuery or underscore, an existing javascript library. You want to consume those from your typescript code.


2 Answers

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).

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 
like image 82
Fenton Avatar answered Oct 22 '22 17:10

Fenton


The question is a bit old, but for the sake of people coming from search engines like me, if you are looking for an automated tool, check out:

  • Microsoft/dts-gen

    The official starting point Microsoft uses when creating types. It's meant to be a starting point only though and I didn't get a lot of luck depending just on it

  • dtsmake

    This one looks very promising. It depends on Ternjs which some editors use to provide autocomplete for JS code. Check Ternjs out also for other tool names and comparisons with them.

Update (2021): It's a good idea to check npmtrends and compare dts-generator, dts-gen, dtsmake, npm-dts, and alternatives.

like image 32
Meligy Avatar answered Oct 22 '22 15:10

Meligy