
"When you assign the any type to a variable, you're essentially telling the compiler: Stop checking this. I'll handle it myself. At that moment, you've basically turned off TypeScript. Even worse, any tends to spread through a codebase. If a function returns any, every variable that receives that value becomes untyped as well."
"Instead, use unknown. It behaves like a safer version of any. You can store anything in an unknown variable, but TypeScript won't let you access properties or call methods until you explicitly check the value. The unknown type works especially well for: API responses user input error objects in catch blocks."
"The as keyword is a type assertion. It forces TypeScript to trust you. Sometimes that's necessary – but it can also hide real errors. TypeScript 4.9 introduced a better tool: satisfies. Instead of blindly accepting your assertion, it checks whether the object actually matches the expected type."
TypeScript's type system offers powerful bug prevention capabilities, but many developers underutilize it by using any to bypass type checking. The any type disables TypeScript's compiler checks and spreads throughout codebases, causing runtime crashes. The unknown type provides a safer alternative, requiring explicit type checking before accessing properties or methods. This approach works well for API responses, user input, and error objects where data shape is uncertain. Type assertions using as can hide errors, while TypeScript 4.9's satisfies keyword offers better validation by checking object conformance to expected types without losing type information.
#typescript-type-safety #unknown-vs-any #type-assertions #satisfies-keyword #runtime-error-prevention
Read at jsdevspace.substack.com
Unable to calculate read time
Collection
[
|
...
]