Mixing TypeScript and JavaScript
TypeScript and JavaScript files can live in the same project, and declaration files describe the types of JavaScript code that has none.
Plan a gradual migration using JavaScript checking, declaration files and typed modules.
Few teams start with TypeScript on day one. Usually there is already a JavaScript codebase, plus libraries written in JavaScript. The good news is that you never have to convert everything at once. TypeScript was designed to live alongside JavaScript.
The rule
JavaScript and TypeScript share a project; declaration files carry the types.
Four tools make this work.
allowJs — a compiler option that lets .js files be part of a TypeScript project. A .ts file can import from a .js file and vice versa, so you can convert one file at a time.
checkJs or // @ts-check — asks TypeScript to check JavaScript files too. checkJs turns it on for all of them; a // @ts-check comment at the top turns it on for a single file. In JavaScript you can add types through JSDoc comments:
// @ts-check
/** @param {{ id: number, title: string }} task */
function formatTask(task) {
return task.id + ". " + task.title;
}
formatTask({ id: 1 }); // error: property 'title' is missingDeclaration files (.d.ts) — files that contain only types, no code. They describe the shape of JavaScript code so TypeScript can check your use of it:
// legacy-store.d.ts
export function loadTasks(): { id: number; title: string; done: boolean }[];@types packages — declaration files for popular JavaScript libraries, published separately. If a library ships without types, npm install --save-dev @types/<library> often provides them. Many modern libraries include their own .d.ts files, so nothing extra is needed.