Sub topic 1
Converting a JavaScript File to TypeScript
Prerequisites
This chapter assumes working knowledge of modern JavaScript, Node.js, npm, and terminal commands. You should know how functions, objects, arrays, and imports work. TypeScript adds static types that the compiler checks before your code runs.
Plan the Migration
Migrate one small, well-tested file at a time. Start with a file that has few dependencies and clear inputs and outputs. Keep the application working after each change.
A practical sequence is:
- Add TypeScript without changing application behavior.
- Let JavaScript and TypeScript compile together.
- Check one JavaScript file.
- Rename that file to
.ts. - Fix compiler errors in small groups.
- Run tests after each group.
Do not begin by turning on every strict option. First establish a repeatable build, then increase checking.
Install TypeScript and Create tsconfig.json
Install the compiler and Node.js declarations as development dependencies. A tsconfig.json file tells the compiler which files to include and how to compile them.
npm install --save-dev typescript @types/node
npx tsc --initUse a configuration that writes compiled files to dist:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "src",
"outDir": "dist",
"allowJs": true,
"checkJs": false,
"strict": false
},
"include": ["src"]
}Let JavaScript and TypeScript Coexist
allowJs permits .js and .ts files in the same project. Set checkJs to true when you want TypeScript to report errors in JavaScript files. You can also opt in for one file:
// @ts-check
/** @param {{ name: string }} user */
function greet(user) {
return `Hello, ${user.name}`;
}This gives useful feedback before renaming the file.
Rename the File
Rename a selected file from src/user.js to src/user.ts. Update imports if their paths or module style require it. The compiler will now inspect TypeScript syntax and report problems that JavaScript checking may have missed.
Read and Triage Compiler Errors
Run the compiler without emitting files:
npx tsc --noEmitFix errors in this order:
- Syntax and module-resolution errors.
- Missing parameter or return types.
- Invalid object properties.
nullandundefinedcases.- Errors caused by third-party packages.
Fix the earliest error first because later messages may be consequences of it. Prefer a real type or a runtime check over suppressing the error.
Exercise
Why should a migration begin with one small file?
Show answer
A small file limits the number of errors, keeps behavior easier to verify, and makes each change reversible.