What are *.d.ts files for?
The definition files generated by the TypeScript compiler are indeed mostly a repeat of the code you wrote but with some notable differences:
- They don't contain implementation, only declarations
- They only contain publicly accessible types
The use case for these declaration files is for distributing libraries. You can distribute a library without the original TypeScript code (as that does not matter at runtime anyway) and distribute just the compiled JavaScript. JavaScript consumers will use the JavaScript and not care about its origin. TypeScript consumers will also use the JavaScript at runtime, but the .d.ts
files will allow the compiler to check the code even though the original TypeScript source for the library is not present.
This same approach could be also used to break up a large project into several smaller projects that use the declaration files to establish the interface between them. Each project can be recompiled independently without recompiling all of them, reducing compilation times. The TypeScript compiler is actually planning to add buit-in support for this in the future.
If you have a JavaScript file and you want to add rich type information to it, you can do that in a declaration file. It's like splitting your TypeScript between two files; a JavaScript file .js
with only plain JavaScript, and a declaration file .d.ts
with all the type information.
This means there is some redundancy between the files.
Commonly, if you write a TypeScript library you auto-generate the JavaScript and declaration file and package those rather than the original TypeScript. It means the library can be consumed from JavaScript and TypeScript applications and allows the consuming library to use different TypeScript version than your library.
If you have JavaScript files you want to include in compilation, you don't have to create a declaration file - IDEs allow TypeScript-style inference within JavaScript (for example, VS Code allows the // @ts-check
comment) and the compiler allows JavaScript to be included in compilation if you so wish.