Mixing TypeScript and JavaScript
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.
The shortcut
When TypeScript complains about JavaScript code, ask "Where are the types for this coming from?"
- My own
.jsfile → enableallowJs, and add JSDoc or convert it to.ts. - A library → check whether it ships types, then look for
@types/<name>. - Neither exists → write a small
.d.tsfile yourself.
Let both languages in
Set
"allowJs": truein tsconfig.json. Every existing .js file still compiles.
The trap is renaming all files to .ts in one go. You face hundreds of errors at once and the team stops shipping. Convert gradually.
Drills
Answer fast — trust the rule.
Which compiler option lets .js files be included in a TypeScript project?
What does a .d.ts file contain?
You install a JavaScript library and TypeScript says it cannot find its types. What do you try first?
How do you get type checking in a single JavaScript file without renaming it?
Remember
- JavaScript and TypeScript share a project; declaration files carry the types.
- Ask "where are the types coming from?": own file, library, or a hand-written
.d.ts. - Trap: converting everything at once — migrate one file at a time.
