TypeScript Type Inference
TypeScript is smart enough to figure out the type of a variable automatically based on the value you assign to it, even without an explicit annotation. This is called type inference.
Because of inference, you often don't need to write types everywhere. TypeScript infers types for variables, function return values, and more, while still catching type errors if you later try to misuse the variable.
let city = "Paris"; // inferred as stringInference for variables
When you write `let city = "Paris";`, TypeScript infers that city is a string, even though you never wrote `: string`. It will still flag an error if you later assign a number to city.
Inference for return values
TypeScript can also infer a function's return type from its body, so writing the return type explicitly is often optional but can still be useful for documentation.
let city = "Paris";
console.log(typeof city);stringTypeScript infers that city is a string from its initial value.
function double(n: number) {
return n * 2;
}
const result = double(4);
console.log(result);8TypeScript infers that double returns a number, without an explicit return type annotation.
Key points
- Type inference lets TypeScript detect types without explicit annotations.
- Inferred types are just as strict as annotated types.
- Function return types can also be inferred from the function body.
- Explicit annotations are still useful for clarity in public APIs.
