TypeScript in Practice

Shipping with confidence · Lesson 10 of 12 · 17 min

Migrating to strict mode

Turning on strict in a large project can produce thousands of errors. Don't fix them all at once. Migrate file by file, and make sure nothing new slips in.

Measure

npx tsc --noEmit --strict | grep -c "error TS"

Write the number down. It's your progress bar.

Turn it on, with an escape hatch

Enable strict and add // @ts-expect-error above each existing error with a script. New code is strict from day one.

Fix one folder per week

Start with lib/ and shared types: fixing them removes errors everywhere else.

Block regressions in CI

Fail the build if the number of @ts-expect-error comments goes up.

The most common fixes

ErrorUsual fix
Object is possibly undefinedEarly return or optional chaining
Parameter implicitly has an any typeAdd the type, or infer it from a callback
Not all code paths return a valueAdd the missing return

Avoid the "fix" of adding ! everywhere. Each non-null assertion is a bug you've hidden, not fixed.