Introduction to JavaScript and TypeScript Migration
Migrating JavaScript to TypeScript means introducing static type checking into an existing JavaScript application. The goal is not to rewrite the entire application immediately. Instead, you gradually introduce TypeScript features, identify potential errors earlier, and improve maintainability while keeping the application functional.
TypeScript is a superset of JavaScript. Most valid JavaScript syntax is also valid TypeScript, which makes incremental migration possible. TypeScript adds features such as type annotations, interfaces, generics, and compile-time checks. The TypeScript compiler then transforms TypeScript code into JavaScript that can run in supported JavaScript environments.
A successful migration focuses on manageable steps, accurate types, and continuous validation. A small project might migrate quickly, while a large application can introduce TypeScript module by module without changing every file at once.
Why Migrate an Existing JavaScript Project?
JavaScript allows variables and function parameters to hold different kinds of values at runtime. This flexibility is useful, but it can also allow mistakes to remain unnoticed until a particular execution path runs.
JavaScript example
function calculateTotal(price, quantity) {
return price * quantity;
}
const total = calculateTotal("ten", 2);
console.log(total);
JavaScript permits the call even though the price is not a valid numeric value for this calculation. The result is NaN, which may cause problems later in the application.
TypeScript can report this mismatch during development when the function's parameters are correctly typed. It also improves editor suggestions, makes function contracts clearer, and helps developers safely refactor code.
- Earlier error detection: Identify many type-related problems before executing the application.
- Better editor support: Improve autocomplete, navigation, and refactoring assistance.
- Clearer contracts: Document the expected input and output of functions and objects.
- Safer maintenance: Detect some breaking changes when models, functions, or API responses evolve.
- Incremental adoption: Keep existing JavaScript modules while gradually converting selected files.
Step 1: Inspect the Existing Project
Before changing configuration or file extensions, understand the structure of the project. Identify its build system, test framework, package manager, module format, and current deployment process.
Pay particular attention to files that import or export modules, use third-party libraries, process environment variables, or depend on browser and Node.js APIs. These areas may require TypeScript configuration or additional type definitions.
project/
src/
services/
components/
utils/
index.js
tests/
package.json
Run the existing tests and build before starting the migration. This establishes a baseline so that you can distinguish existing problems from issues introduced during conversion. Use source control and migrate in small, reviewable changes.
Step 2: Install and Configure TypeScript
For an npm-based project, install TypeScript as a development dependency. Projects using React, Node.js, or other frameworks may also need framework-specific type definitions and build-tool configuration.
npm install --save-dev typescript
npx tsc --init
The configuration file, tsconfig.json, controls how TypeScript checks and compiles files. Its options should reflect the existing project's runtime, module system, and build process rather than blindly copying a configuration intended for another environment.
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"moduleResolution": "node",
"allowJs": true,
"checkJs": false,
"strict": false,
"noEmit": true,
"skipLibCheck": true
},
"include": ["src/**/*"]
}
This is an illustrative starting configuration, not a universal configuration. The module and module-resolution options must match your toolchain. For a modern ESM application, a different module configuration may be appropriate. The noEmit option is suitable when another tool handles compilation; remove or adjust it when using TypeScript to emit JavaScript.
The allowJs option lets JavaScript files participate in a TypeScript project. Starting with checkJs disabled and strict disabled can reduce the initial number of reported errors. These are transitional choices, not necessarily the desired final settings.
Step 3: Enable JavaScript Checking Gradually
You do not need to convert every file before receiving benefits from TypeScript. With allowJs enabled, you can add JSDoc annotations to existing JavaScript files and ask TypeScript to check them.
For example, add a JSDoc comment to a JavaScript function to describe the types of its parameters and return value.
/**
* Calculates the total price.
* @param {number} price
* @param {number} quantity
* @returns {number}
*/
function calculateTotal(price, quantity) {
return price * quantity;
}
calculateTotal(10, 3);
// TypeScript can check this call.
calculateTotal("ten", 3);
// TypeScript reports a type error when this
// JavaScript file is checked.
Once the team is ready, enable checkJs to check eligible JavaScript files. Review errors by module and resolve them progressively. This approach is useful when the project contains a substantial amount of existing code that should remain operational throughout the migration.
Step 4: Convert JavaScript Files to TypeScript
Begin with a small, self-contained module such as a utility function or calculation service. Rename its extension from .js to .ts, then add type annotations and resolve the resulting compiler errors.
Before: JavaScript
function calculateTotal(price, quantity) {
return price * quantity;
}
module.exports = { calculateTotal };
After: TypeScript
export function calculateTotal(
price: number,
quantity: number
): number {
return price * quantity;
}
This conversion introduces explicit parameter and return types and uses ES module syntax. The export style must match the project's module system; changing CommonJS to ES modules may require updates to imports, tests, or build configuration. TypeScript can also work with CommonJS when configured appropriately.
After conversion, update import paths or file references where necessary, run the type checker, and execute the tests. Do not rename every file at once. Keep each change small enough to review and validate independently.
Step 5: Add Types to Objects and Functions
Existing JavaScript projects often pass objects between components, services, and API functions. Define interfaces or type aliases for important data structures so that the expected shape becomes explicit.
interface Product {
id: number;
name: string;
price: number;
inStock: boolean;
}
function formatProduct(product: Product): string {
return product.name + " - " + product.price;
}
const keyboard: Product = {
id: 101,
name: "Keyboard",
price: 45,
inStock: true
};
console.log(formatProduct(keyboard));
Introduce types first at important boundaries: public function parameters, shared models, service return values, and data passed between modules. Type inference can handle many local variables without explicit annotations, so avoid adding redundant types everywhere.
When a value can genuinely be absent, model that possibility with an optional property or an appropriate union type. Do not mark properties as optional merely to silence errors when the application requires them to exist.
Step 6: Handle Third-Party Libraries and Existing APIs
Some JavaScript libraries include their own TypeScript declarations, while others rely on community-maintained definitions. Check the library's documentation and package metadata before installing additional types.
npm install --save-dev @types/lodash
Use a package such as @types/lodash only when it is appropriate for the installed library and the library does not already provide the necessary declarations. Avoid adding duplicate or incompatible definitions.
Type annotations also do not validate incoming JSON at runtime. An API response may differ from its declared TypeScript type because of a server change, malformed data, or an unexpected network response. Use runtime validation when the application must verify external data before trusting it.
interface User {
id: number;
name: string;
}
async function fetchUsers(): Promise {
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error("Unable to fetch users");
}
const data: unknown = await response.json();
if (!Array.isArray(data)) {
throw new Error("Invalid users response");
}
// Validate each element's required fields here
// before treating the values as User objects.
throw new Error("Add application-specific validation");
}
The final example intentionally stops before returning the parsed data because checking only that a value is an array does not establish that its elements satisfy the User interface. Implement validation for each required field, or use a runtime schema-validation library, before converting untrusted data to a trusted application model.
Step 7: Reduce Unsafe Types
During migration, any can be tempting because it suppresses many useful checks. However, replacing every JavaScript value with any provides little type safety and makes future refactoring harder.
Prefer specific interfaces, union types, or unknown for values whose types are not known yet. With unknown, TypeScript requires you to check or narrow a value before using it in a type-specific operation.
function displayValue(value: unknown): string {
if (typeof value === "string") {
return value;
}
if (typeof value === "number") {
return String(value);
}
return "Unsupported value";
}
Keep a list of temporary any annotations and remove them as the relevant code becomes better understood. Enable stricter compiler options incrementally, resolve the resulting errors, and use the compiler to reinforce the type-safety improvements made during migration.
Step 8: Update the Build and Test Workflow
A migration is incomplete if TypeScript is checked locally but ignored in continuous integration or production builds. Add an appropriate type-check command to the package scripts and ensure the deployment pipeline runs it.
{
"scripts": {
"typecheck": "tsc --noEmit",
"test": "your-existing-test-command",
"build": "your-existing-build-command"
}
}
Replace the placeholder test and build commands with the commands already used by your project. Some build tools transpile TypeScript without performing full type checking, so an explicit type-checking step may still be necessary. Confirm that the compiler includes the files you intend to validate.
For each migrated module, verify its imports and exports, relevant unit tests, application behavior, and production build. Once conversion is stable, consider enabling strict and other useful compiler checks in stages instead of leaving the project permanently dependent on permissive settings.
Common Migration Mistakes
Converting every file in one change
A large conversion makes errors harder to isolate and code reviews more difficult. Prefer a sequence of small, tested changes.
Using any to silence errors
Excessive any removes many of the checks that motivate migration. Use accurate types or unknown with appropriate narrowing.
Ignoring the runtime and module system
Compiler settings that work in a browser application may not suit a Node.js application. Match the configuration to the existing build and deployment environment.
Assuming types validate API data
TypeScript annotations are removed during compilation. External data still needs runtime validation whenever correctness or security depends on its shape.
Skipping tests and production checks
A project can type-check successfully and still have runtime or configuration problems. Keep tests and production build checks in the migration workflow.
A Practical Migration Checklist
Use this sequence to make progress without destabilizing the application:
- Record the current build and test status and commit a stable baseline.
- Install TypeScript and create a configuration that matches the project.
- Enable JavaScript support with
allowJsand introduce JSDoc where useful. - Convert a small utility module and add meaningful parameter and return types.
- Define types for shared models, service boundaries, and important function contracts.
- Resolve module imports, dependency types, compiler errors, and runtime validation requirements.
- Run tests and production builds after each meaningful migration step.
- Increase compiler strictness gradually and remove temporary unsafe types.
- Enforce type checking in the continuous integration pipeline.
Conclusion
Migrating JavaScript to TypeScript is an incremental engineering process. You can begin with compiler configuration and JSDoc, convert independent modules, define reliable models, and progressively enable stricter checks. There is no requirement to change the entire codebase in a single release.
The most effective migration improves the codebase without interrupting normal development. By combining small changes, explicit types, runtime validation, automated tests, and continuous type checking, you can build a safer and more maintainable application while preserving the value of existing JavaScript code.