Course outline · 0% complete

0/26 lessons0%

Course overview →

Migrating a JavaScript File

lesson 8-2 · ~11 min · 25/26

JS to TS in four moves

Because every JavaScript file is nearly valid TypeScript, migration is incremental:

  1. Rename file.js to file.ts. It mostly compiles as is
  2. Annotate parameters, the compiler flags each implicit any for you under strict mode
  3. Extract interfaces for the object shapes flowing through the code, like Unit 3
  4. Chase the remaining errors, most are real latent bugs being surfaced

Here is step 3 in action. The JavaScript version passed bare objects around, the TypeScript version names the shape:

interface Item {
  name: string;
  qty: number;
}

function receipt(items: Item[]): string

Teams migrate large codebases file by file this way, TypeScript and JavaScript coexist in one project while it happens.

1. rename .js → .ts2. annotate parameters4. fix surfaced bugs3. extract interfaces
The migration loop: rename, annotate, extract shapes, then fix what the compiler surfaces.

Code exercise · typescript

The migrated receipt function, fully typed. Run it, then delete the Item interface and both annotations to see it still run, that is why migration can be gradual: the types are checks, not behavior.

Code exercise · typescript

Your turn: migrate this JavaScript. The function works but has no types. Annotate prices as number[], shipping as number, and add the number return type, keeping the output identical.

Quiz

During migration a renamed .ts file produces 30 errors. What are they, most likely?