Eliminating any; preferring unknown + narrowing
Replace any with unknown + narrowing; add small guards and assertion functions; toggle strict flags gradually without breaking the build.
Intro
Goal: Remove any hotspots. Prefer unknown for untrusted values and narrow with simple checks. You will add tiny guards and enable strict flags step by step.
- any → unknown
- typeof/in/instanceof narrowing
- assertion functions
any pitfalls
any turns off safety: wrong shapes or string math slip through compile-time, failing later.
// any hides bugs
function avgBad(values: any): number {
// Compiles even if values is not an array of numbers
return values.reduce((a: number, b: number) => a + b, 0) / values.length
}
// Runtime crash examples:
// avgBad(123)
// avgBad(["1","2"]) // string addition!All lessons in this course
- Eliminating any; preferring unknown + narrowing
- Enforcing strict flags gradually