BeCuriouzLearn something new every day
How TypeScript Learns the Types of JavaScript It Can't See
💡 A .d.ts file describes the types of JavaScript that has no runtime code of its own, and @types/* packages from DefinitelyTyped supply those descriptions for libraries that don't ship their own.
Not every library ships with types. Plenty of npm packages are written in plain JavaScript, so the compiler has no idea what shapes their functions and objects have. That's where declaration files come in — files ending in .d.ts that contain only type information: signatures, interfaces, and declare statements, with no runtime code. Think of a .d.ts as a contract that describes JavaScript that lives somewhere else.
Inside a declaration file you'll see the declare keyword, which says "this thing exists at runtime — trust me — here is its type." For example, describing a tiny JS module:
// leftpad.d.ts
declare module "leftpad" {
export function leftpad(str: string, len: number): string;
}When a library authors these files itself, it points to them via the "types" field in package.json, and you get autocomplete for free. But what about the thousands of older JS-only packages? The community maintains DefinitelyTyped, a giant GitHub repository of .d.ts files contributed for popular libraries. These are published to npm under the @types scope.
So to type-check code that uses Lodash, you install the library and its separate types package:
npm install lodash
npm install --save-dev @types/lodashTypeScript automatically looks in node_modules/@types and picks these up — no imports or config needed. If a package already bundles its own types (like Axios), you don't need an @types package at all; installing one would be redundant.