TypeScript and JavaScript
Overview
Most TypeScript projects didn’t start as TypeScript. You’ll often join a codebase that’s half JavaScript, or want type checking in a project that can’t add a build step. TypeScript handles both: it can type-check plain JavaScript, read types from JSDoc comments, and let .js and .ts files live side by side while you migrate.
Type-checking JavaScript
Add one comment at the top of a .js file:
// @ts-check
const total = "10" * 2;
// error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.Even without any annotations, TypeScript infers types from your code and catches misspelled properties, wrong method names, missing arguments and suspicious arithmetic. In VS Code, // @ts-check works in any JavaScript file — no tsconfig needed.
For a whole project, set it in tsconfig:
{ "compilerOptions": { "allowJs": true, "checkJs": true } }// @ts-nocheck turns checking off for a single file.
Types in JSDoc comments
TypeScript understands JSDoc, the standard comment format for documenting JavaScript. You can express nearly every TypeScript type in it:
// @ts-check
/**
* @typedef {object} Item
* @property {string} name
* @property {number} price
* @property {number} [quantity] - square brackets: optional
*/
/**
* @param {Item[]} items
* @param {"SAVE10" | "HALF"} [coupon]
* @returns {number}
*/
export function cartTotal(items, coupon) { … }
/** @type {Map<string, Item>} */
const cache = new Map();
/**
* @template T
* @param {T[]} items
* @returns {T | undefined}
*/
export function first(items) {
return items[0];
}| JSDoc | TypeScript equivalent |
|---|---|
@param {string} name |
name: string |
@param {number} [age] |
age?: number |
@returns {boolean} |
: boolean return type |
@type {string[]} |
const x: string[] |
@typedef {object} User + @property |
type User = { … } |
@typedef {import("./types.ts").User} User |
import type { User } |
@template T |
<T> |
/** @type {const} */ ([1, 2]) |
[1, 2] as const |
TypeScript 7 aligned JavaScript checking more closely with .ts checking. A few older JSDoc conventions (Closure-style function types, @enum) are no longer special, and you must write typeof x when using a value as a type — the TypeScript 7 release notes list the details.
Why JSDoc instead of .ts?
Some teams and libraries deliberately keep JavaScript source with JSDoc types: no compilation step, and the files run anywhere as they are, while editors and CI still get full type checking. It’s more verbose than TypeScript syntax, and complex types are awkward to write in comments — a common compromise is to put complex types in a .ts or .d.ts file and import them with @typedef {import(…)}.
Mixing .js and .ts
With allowJs, TypeScript files can import JavaScript files and vice versa:
// main.ts
import { cartTotal } from "./cart.js"; // typed from the JSDoc (or a .d.ts next to it)Imports from unchecked JavaScript without JSDoc are inferred where possible and any where not — another reason to add types as you go.
A migration plan
Converting a large codebase in one go rarely works. A gradual path:
- Add TypeScript with
allowJs. Installtypescript, add a tsconfig withallowJs: true, and gettsc --noEmitrunning in CI. Nothing is checked yet, but the tooling is in place. - Turn on checking. Enable
checkJs(or add// @ts-checkfile by file). Fix the real bugs it finds — there are usually some — and add JSDoc to the most important functions. - Rename files to
.ts, one at a time. Start with the leaves: utilities and data models that import little. Each converted file gives better types to everything that imports it. Write new files in TypeScript from day one. - Tighten strictness. If you started with
"strict": falseto keep errors manageable, enable the strict flags one at a time (noImplicitAny, thenstrictNullChecks, …) and fix the errors.
Tips:
- Don’t try to perfect types during the move —
unknownand a// TODOare fine;anyshould be rare and searchable. - Keep each step small enough to review and ship. A project that’s 60% TypeScript and green in CI beats a big-bang branch that never merges.
- Track progress by counting
.jsfiles andanys over time.
The other direction: JavaScript from TypeScript
TypeScript is always valid input for type-stripping tools, so “converting back” is trivial — strip the types (Node, esbuild or tsc will do it) and you have JavaScript. That’s part of why adopting TypeScript is low-risk.
Remember: TypeScript checks JavaScript too. Use
// @ts-checkand JSDoc to get types without a build step, andallowJsto migrate one file at a time.
Type-check a JavaScript file with JSDoc
The starter src/cart.js is plain JavaScript with a hidden bug. Add // @ts-check and JSDoc types: a @typedef for Item (name, price, quantity), @param and @returns on lineTotal, cartTotal and applyCoupon (whose code is the union "SAVE10" | "HALF"). TypeScript will flag the bug — fix it in the JavaScript. Then import the functions into src/main.ts, compute the total of the sample cart with coupon "SAVE10", and print it with 2 decimals (Total: 52.20). Show with // @ts-expect-error in main.ts that applyCoupon(10, "FREE") is rejected. (The test project enables allowJs and checkJs.)
// ---- src/cart.js ----
export function lineTotal(item) {
return item.price * item.quantity;
}
export function cartTotal(items) {
return items.reduce((sum, item) => sum + lineTotal(item), "0");
}
export function applyCoupon(total, code) {
if (code === "SAVE10") return total * 0.9;
if (code === "HALF") return total / 2;
return total;
}
// ---- src/main.ts ----// ---- src/cart.js ----
// @ts-check
/**
* @typedef {object} Item
* @property {string} name
* @property {number} price
* @property {number} quantity
*/
/**
* @param {Item} item
* @returns {number}
*/
export function lineTotal(item) {
return item.price * item.quantity;
}
/**
* @param {Item[]} items
* @returns {number}
*/
export function cartTotal(items) {
// The bug: the starting value was the string "0", so the "sum" was string concatenation.
return items.reduce((sum, item) => sum + lineTotal(item), 0);
}
/**
* @param {number} total
* @param {"SAVE10" | "HALF"} code
* @returns {number}
*/
export function applyCoupon(total, code) {
if (code === "SAVE10") return total * 0.9;
if (code === "HALF") return total / 2;
return total;
}
// ---- src/main.ts ----
import { applyCoupon, cartTotal } from "./cart.js";
const items = [
{ name: "Lamp", price: 24.5, quantity: 2 },
{ name: "Notebook", price: 3, quantity: 3 },
];
console.log(`Total: ${applyCoupon(cartTotal(items), "SAVE10").toFixed(2)}`); // Total: 52.20
// @ts-expect-error -- "FREE" is not an accepted code
applyCoupon(10, "FREE");Summary
- TypeScript can check JavaScript: add
// @ts-checkto a file, or turn oncheckJsfor the whole project. - JSDoc comments carry types in .js files:
@param,@returns,@type,@typedef,@template. allowJslets .ts and .js files import each other, so a project can move to TypeScript one file at a time.- Migrate gradually: allowJs → checkJs with JSDoc → rename files to .ts → tighten strictness.
- Some libraries ship JavaScript with JSDoc types and generate .d.ts files from them — no build step for the source.