Sub topic 4
Rename the file from .js to .ts
This chapter covers the rename step: what to check first, how to rename safely, and what changes the moment the compiler treats the file as TypeScript. It assumes you have a working tsconfig.json with allowJs: true (as in the earlier setup chapters), typescript and @types/node installed, and a project under Git. It does not cover how to fix each error. The next chapter covers that.
What a rename actually changes
Before the rename, the compiler treats your file as JavaScript. With allowJs on and checkJs off, it reads the file and emits it, but it reports almost no errors. After the rename, the compiler applies full TypeScript rules to the file. Nothing else changes: the code is the same, and the file is still plain JavaScript syntax. The file now has to satisfy the type checker.
Three things change at once:
- Type errors are reported. Many of them were always latent bugs or missing information.
- JSDoc type comments stop counting. In a
.tsfile, the compiler ignores@param {string}and@returnstype annotations. Types must be written as TypeScript syntax. - CommonJS idioms such as
module.exportsare no longer given special treatment. In.jsfiles the compiler understands them. In.tsfiles they only work because@types/nodedeclaresmoduleandrequire, and the results are loosely typed.
Prepare before you rename
Do this in order. It keeps the rename reviewable and gives you a baseline.
- Pick one leaf file. Choose a file that few other files import, or one that imports little. A utility module is a better first target than an application entry point.
- Make sure your working tree is clean and your tests pass.
- Run the compiler once and record the result:
npx tsc --noEmitThe --noEmit flag type-checks without writing any files to dist. If this already reports errors, note them. You need to tell old errors from new ones after the rename.
Rename with Git
Use git mv so Git records the operation as a rename:
git mv src/report.js src/report.ts
git commit -m "Rename report.js to report.ts (no content changes)"Commit the rename with no edits to the contents. Git detects renames by content similarity. If you rename and rewrite heavily in one commit, git log --follow and blame can lose the file's history. A separate commit also gives you a clean revert point if the file turns out to be harder than expected.
Pick the right extension
The extension tells the compiler how to parse the file and which module format it uses.
| JavaScript file | TypeScript file | Notes |
|---|---|---|
| `.js` | `.ts` | Standard case |
| `.jsx` | `.tsx` | Required if the file contains JSX. Needs the `jsx` option in `tsconfig.json` |
| `.mjs` | `.mts` | Always an ES module |
| `.cjs` | `.cts` | Always CommonJS |
Do not use .ts for a file that contains JSX. The syntax will fail to parse. If you are unsure whether a .js file contains JSX, search it for < tags that sit inside return statements.
A worked example
Here is a small file, src/report.js, before the rename:
const fs = require("fs");
function formatUser(user) {
return user.name.toUpperCase() + " (" + user.age + ")";
}
const options = {};
options.verbose = true;
function save(path, users) {
const lines = users.map(formatUser).join("\n");
fs.writeFileSync(path, lines);
}
module.exports = { formatUser, save, options };After git mv, run npx tsc --noEmit. With strict set to false, as in the starter configuration, you get a single error:
src/report.ts:8:9 - error TS2339: Property 'verbose' does not exist on type '{}'.The compiler inferred the type of options as {} (an object with no properties) from the empty literal. JavaScript lets you add properties later. TypeScript does not, because it cannot know the object's shape. This is a typical first error. The next chapter covers how to read and rank errors like it, and a later chapter covers interfaces for object shapes. For now, a minimal fix is to declare the shape where the object is created:
const options = { verbose: false };The two parameters of formatUser and save are still typed any, and nothing complains. That is the effect of noImplicitAny being off. It is useful at this stage, because you can get a compiling .ts file first and add types after.
Remove the CommonJS leftovers
A .ts file with no import or export statements is treated as a script, not a module. Everything declared at its top level lives in the global scope. This causes a confusing error when two renamed files both declare the same name:
src/report.ts:1:7 - error TS2451: Cannot redeclare block-scoped variable 'fs'.The compiler is saying that fs is declared in another script file too. Using require and module.exports does not make the file a module in TypeScript's eyes. The fix is to switch to ES module syntax, which the compiler then emits as CommonJS because of "module": "commonjs":
import fs from "fs";
export function formatUser(user: { name: string; age: number }): string {
return user.name.toUpperCase() + " (" + user.age + ")";
}
export const options = { verbose: false };
export function save(path: string, users: { name: string; age: number }[]): void {
const lines = users.map(formatUser).join("\n");
fs.writeFileSync(path, lines);
}import fs from "fs" works because esModuleInterop is on in the starter configuration. Other files that still call require("./report") keep working, because the emitted JavaScript sets exports.formatUser and the other exports the same way module.exports did.
If you are not ready to convert the imports yet, a one-line stopgap makes the file a module: export {};. Treat it as temporary.
Update everything that points at the old file
Renaming a file silently breaks references that are not imports. Search the project for the old file name (grep -r "report.js") and check these places:
package.jsonfields such asmain,bin,exportsandscripts. These should point to compiled output indist, not to the source file.- Test runner configuration and glob patterns. A pattern like
**/*.test.jswill skip your renamed test files. - ESLint, Prettier and bundler configuration that lists extensions.
- Dockerfiles and CI scripts that run
node src/report.jsdirectly. Node cannot run.tsfiles without a build step, covered in the chapter on compiling and running.
Imports from other files need no edits if they omit the extension. Imports that spell out ./report.js do. After the rename, they point to a path that exists only in the build output.
Keep the JavaScript copy out of the way
Never keep report.js and report.ts side by side in the same folder. Both compile to dist/report.js, and the compiler stops with an error like this:
error TS5056: Cannot write file 'dist/report.js' because it would be overwritten by multiple input files.This often happens when someone copies a file instead of using git mv. Delete the old file and let version control hold it.
Common mistakes
- Renaming many files in one step. You then face hundreds of errors from different causes and cannot tell which change produced which error.
- Silencing the first errors with
// @ts-ignore. A comment that suppresses an error also hides it from the reviewer. If you must suppress,// @ts-expect-erroris better, because the compiler reports an error when the suppression becomes unnecessary. - Leaving JSDoc types in place and assuming they still apply. In the
.tsfile they are only comments. - Reading "no errors" as "well typed". With
strictoff, an untyped parameter isany, andanyaccepts everything. A clean compile only means no checks were violated.
Exercise
You run git mv src/util.js src/util.ts, then npx tsc --noEmit, and see TS2451: Cannot redeclare block-scoped variable 'path' pointing at util.ts and at another renamed file, src/cli.ts. Both files start with const path = require("path"); and neither contains an import or export statement. Explain the cause and give a fix that does not rename or merge any files.
Show answer
Files without import or export are treated as scripts, so their top-level const path declarations share the global scope and collide. Using require does not make a file a module. The fix is to make each file a module, preferably by replacing the require line with import path from "path"; (works with esModuleInterop) and exporting what other files need. A temporary fix is to add export {}; to each file.