#typescript
#config
#declarations
Day 26: Declaration Files (.d.ts)
The Missing Link
Welcome to Day 26! Sometimes you download a library and TS yells: “Could not find a declaration file for module ‘xyz’”.
What is a .d.ts file?
It’s a file that contains only type definitions, no logic. It describes the shape of an existing JavaScript library to TypeScript.
DefinitelyTyped (@types)
First, always check if types exist.
npm install --save-dev @types/lodash
This downloads the .d.ts files maintained by the community.
Writing Your Own
If no types exist, create my-lib.d.ts.
// my-lib.d.ts
declare module 'my-lib' {
export function doSomething(param: string): void;
export const version: number;
}
Now you can import it without errors!
import { doSomething } from 'my-lib';
Global Declarations
Sometimes you need to add things to window or global.
declare global {
interface Window {
myAnalytics: any;
}
}
Challenge for Today
- Pretend you have a library
super-math. - Create a file
super-math.d.ts. - Declare a module
super-mathwith a functioncalculate(x: number): number. - Try to “import” it in a .ts file (it won’t run, but TS will be happy).
See you on Day 27 for Configuration!