AI Hints
Home›TypeScript Tutorial›Project: Tests, CLI, Refactoring
TypeScript · Lesson 108 of 120

Project: Refactoring

The compiler helps.

⏱ 2 min read▶ Video at 1:25:21🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

The business adds a new status, returned. In JavaScript, you'd search the code and hope you found every place. In TypeScript, the compiler lists them for you.

Project: Refactoring
From the video: Project: Refactoring
  • A new status
  • JavaScript: hope
  • TypeScript: a list

Adding a status

We add returned to the status union. Now count by status no longer covers every status. Run it. The compiler points straight at the record that needs updating.

app.tstypescript
type Status = "packing" | "shipped" | "delivered" | "cancelled" | "returned";

function countByStatus(statuses: Status[]): Record<Status, number> {
  const counts: Record<Status, number> = { packing: 0, shipped: 0, delivered: 0, cancelled: 0 };
  for (const s of statuses) counts[s]++;
  return counts;
}
Output
app.ts line 4: Property 'returned' is missing in type '{ packing: number; shipped: number; delivered: number; cancelled: number; }' but required in type 'Record<Status, number>'.

Refactoring safely

Change the type first. Let the compiler list every place that breaks. Fix them one by one. When it compiles again, you've found them all. Then run the tests.

keyvalue
Firstchange the type
Thenfollow the errors
Donewhen it compiles
Finallyrun the tests

Summary

Change the type, and let the compiler find every place to update. Next, turning strictness up.

Key takeaways
  • Change the type
  • Follow the errors
  • Compiles = done
Next up: Project: Strictness — turning it all on