Type Inference in TypeScript
TypeScript infers types based on the assigned value, reducing the need for explicit type annotations.
đź§ Main idea:
Type Inference means that TypeScript automatically figures out the type of a variable based on the assigned value, so you don’t always have to manually annotate types.
Simple Example:
TypeScript infers that name is a string, even though you didn’t explicitly write : string.
If you later try to assign a number:
TypeScript will prevent it!
Where Type Inference Happens:
- Variables
- Function Return Types:
Inferred return type: string
- Function Parameters (with Contextual Typing):
Here, num is automatically inferred as number because numbers is an array of numbers.
- Destructuring:
Why is it useful?
- Less code — no need to annotate every variable manually.
- Safer code — still gets all the type-checking benefits.