TypeScript Basics: Understanding Type Annotations
In TypeScript, type annotations are a powerful feature that allows developers to define the types of variables, function arguments, and return values explicitly. This guide explores type annotations in detail.
What Are Type Annotations?
Type annotations explicitly specify the type of a variable, parameter, or return value in TypeScript. They help catch errors during development by ensuring that only values of the correct type are assigned.
Common Type Annotations
1. Basic Types
let isActive: boolean = true; // Boolean type
let age: number = 30; // Number type
let name: string = "John"; // String type
2. Arrays
let numbers: number[] = [1, 2, 3];
let strings: string[] = ["one", "two", "three"];
3. Functions
function add(a: number, b: number): number {
return a + b;
}
4. Objects
let person: { name: string; age: number } = {
name: "Alice",
age: 25
};
5. Union Types
let value: string | number;
value = "Hello"; // Valid
value = 42; // Valid
Using Type Inference
TypeScript can infer types automatically when a variable is initialized. Explicit annotations are not always required.
let inferred = "This is inferred as a string";
Key Points
- Type annotations are optional but highly beneficial.
- Use type inference for simplicity, but add explicit annotations for clarity in complex scenarios.
- Type annotations reduce runtime errors and improve code quality.
Next Steps
The next article will cover:
- Advanced types like interfaces, type aliases, and enums.
- Working with complex structures and type safety.
Stay tuned to explore more TypeScript features!