Basic Type Annotations
Type annotations let you explicitly declare the type of a variable, parameter, or return value. You add a colon followed by the type after the variable name.
Example
// Variable annotations
let name: string = "Alice";
let age: number = 25;
let isActive: boolean = true;
// TypeScript can also infer types
let city = "New York"; // inferred as string
let count = 10; // inferred as number Function Annotations
You can annotate function parameters and return types to ensure functions are called correctly and return the expected type.
Example
// Parameter and return type annotations
function add(a: number, b: number): number {
return a + b;
}
// Arrow function with types
const multiply = (x: number, y: number): number => x * y;
// Void return type
function logMessage(msg: string): void {
console.log(msg);
}
add(5, 3); // OK
add("5", 3); // Error: string is not assignable to number Object Type Annotations
You can describe the shape of objects using inline type annotations.
Example
// Object type annotation
function printUser(user: { name: string; age: number }) {
console.log(`${user.name} is ${user.age} years old`);
}
printUser({ name: "Bob", age: 30 });
// Optional properties with ?
function greet(person: { first: string; last?: string }) {
if (person.last) {
console.log(`Hello, ${person.first} ${person.last}`);
} else {
console.log(`Hello, ${person.first}`);
}
} 