Let TypeScript figure out types with inference, and understand why unknown beats the dangerous any.
Open this lesson in KodokonGood news: you don't have to annotate every variable. Thanks to type inference, TypeScript figures out a variable's type from the value you give it. Writing let city = "Lyon" is enough: TypeScript knows that city is a string and protects it as if you had annotated it.
let city = "Lyon"; // inferred type: string
let count = 3; // inferred type: number
count = count + 1; // accepted
// city = 42; -> error: city is still a stringThe any type means "anything". An any variable escapes all checks: TypeScript accepts everything, without verifying. It is like removing your seatbelt: the code compiles, but errors come back at runtime - exactly what TypeScript was supposed to prevent.
let data: any = "hello";
data = 42; // accepted without complaint
// Compiles, but crashes at runtime:
// data.toUpperCase() does not exist on a number!For a value whose type is genuinely unknown (a server response, user input), prefer unknown. Like any, it accepts any value, but it forces you to check the type (for example with typeof) before using it. Safety therefore remains intact.
let value: unknown = "hello";
// console.log(value.toUpperCase()); -> rejected!
if (typeof value === "string") {
console.log(value.toUpperCase()); // "HELLO"
}