Say for example, you have a npm library, in my case mongoose, how would you go about generating d.ts files?
-
3Possible duplicate of How do you produce a .d.ts "typings" definition file from an existing JavaScript library?Pierre Arlaud– Pierre Arlaud2016-07-26 13:10:00 +00:00Commented Jul 26, 2016 at 13:10
-
For posterity: npmtrends comparing some of the libraries mentioned in this threadfloer32– floer322021-09-08 23:37:25 +00:00Commented Sep 8, 2021 at 23:37
6 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
5 Comments
--declaration and --allowjs are exclusive, so you can't dump definitions from .js files, can you?.ts file in order to generate a starting point .d.ts file. So I'm not using allowJS for this.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:
-
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
-
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.
2 Comments
For other people who find this post through google: there's a generator now by Microsoft itself: dts-gen.
1 Comment
If you're attempting to use a third-party JavaScript library in your TypeScript file, you can create a custom (and nearly blank) declaration file anywhere in your project.
For example, if you wanted to import:
import * as fooLibrary from 'foo-lib';
You would create a new file named 'foo-lib.d.ts' with the following contents:
declare module 'foo-lib' {
var fooLibrary: any;
export = fooLibrary;
}
Comments
For my particular situation, where I was working with obfuscated code from a third party, I found it useful to load the script in a page, and then use the console to log an instance of the obfuscated class. The console gives you a neat summary of the class methods and properties which you can copy and use as the starting point of a definition file.
> o = new ObfuscatedClass()
> console.log(o)
ObfuscatedClass
- methodA(a,b){some implementation}
- methodB(a,b){other implementation} etc
which you can copy paste and edit to
declare class ObfuscatedClass {
methodA(a,b);
methodB(a,b);
}