Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are *.d.ts files for?

In many TypeScript examples files of the *.d.ts type are automatically created at build time. Some of the examples speak of ambient declarations. This though doesn't help me understanding the idea and the sense behind those files, as they basically just repeat what other classes already have.

So why bother creating extra *.d.ts files? How do they help me within my code?

like image 966
Socrates Avatar asked May 22 '18 09:05

Socrates


2 Answers

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.

like image 135
Titian Cernicova-Dragomir Avatar answered Jan 01 '23 20:01

Titian Cernicova-Dragomir


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.

like image 40
Fenton Avatar answered Jan 01 '23 20:01

Fenton