18. Declaration Files & External Libraries
Bridging the Gap with JavaScript
TypeScript is great when you write it from scratch. But the NPM ecosystem is full of millions of libraries written in plain, old JavaScript. If you import a plain JS library, the TypeScript compiler has no idea what functions it contains, and will throw errors. Declaration Files (.d.ts) act as a translator between untyped JS and strict TS.
What is a .d.ts file?
A declaration file ends in .d.ts. It contains zero implementation code (no logic, no math, no console logs). It solely contains type definitions (Interfaces, Types, and function signatures) that describe an external JavaScript file.
Using DefinitelyTyped (@types)
For famous libraries like `lodash` or `react`, the community has already written massive declaration files. You simply download them as dev dependencies.
Writing Custom Declarations (`declare module`)
If you use an obscure, small library that doesn't have `@types` available, you must write a custom declaration file to stop the compiler from complaining. You do this using declare module.
Declaring Global Variables
Sometimes scripts loaded in the <head> of your HTML (like Google Analytics) add variables directly to the global window object. TypeScript doesn't know they exist. You must declare them globally.
Knowledge Check
Ready to test your understanding of 18. Declaration Files & External Libraries?