After this lesson, you will be able to: Read DefinitelyTyped declarations and write your own .d.ts for untyped libraries.
Declaration files are how JS-only libs get TS support. Most you'll use; some you'll write.
DefinitelyTyped is a community-maintained repo of types for popular JS libraries. Install via `npm install --save-dev @types/express`. Imported automatically by tsc when present. Many modern libs ship their own types now (zod, react, vite). Check `package.json` for `"types": "./dist/index.d.ts"`.
For libraries without types (or for ambient declarations).
// types/untyped-lib.d.tsdeclare module "untyped-lib" {export function format(value: string): string;export function parse(input: string): { ok: boolean; data: unknown };export const VERSION: string;}// Or augment global typesdeclare global {interface Window {myCustomAPI: { call(): void };}namespace NodeJS {interface ProcessEnv {DATABASE_URL: string;JWT_SECRET: string;}}}export {}; // marks file as a module
Older approach; modern use ESM imports.
/// <reference path="./types/global.d.ts" />/// <reference types="node" />// Modern equivalent in tsconfig.json:// "types": ["node", "vitest/globals"]// "include": ["src/**/*", "types/**/*"]
Writing declarations for libs that already have built-in types. Check first. Wide types (any, unknown) in declarations. Be specific where you can. Forgetting `export {};` in global augmentations. Without it, declare global isn't recognised. Maintaining stale .d.ts when the library updates. PR back to DefinitelyTyped instead of forking locally.
Pick the cleanest answer.
Sign in and purchase access to unlock this lesson.