TypeScript increases code safety and clarity by using types. Two important concepts in TypeScript are type annotations and type inference.
What are Type Annotations?
Type annotations let you specify variable, parameter, or function return types explicitly.
Example:
let count: number = 5;
function greet(name: string): string {
return 'Hello, ' + name;
}
-
count: numberandname: stringare type annotations. - They help prevent type-related bugs by enforcing how a variable or parameter is used.
What is Type Inference?
Type inference is when TypeScript automatically infers the type based on how a value is assigned or used.
Example:
let score = 10; // TypeScript infers 'score' as number
const isActive = true; // TypeScript infers 'isActive' as boolean
- No explicit annotation needed; TypeScript "guesses" the correct type for you.
When to Use Each?
- Use type annotations when you want to explicitly declare a type or when TypeScript cannot infer the type safely.
- Rely on type inference for simple assignments, but switch to annotations for clarity or stricter checking.
Summary
- Type annotations: You declare the type. Gives clarity and strictness.
- Type inference: TypeScript figures out the type. Saves time and reduces boilerplate in common cases.
Top comments (0)