Type Annotations
Type annotations tell TypeScript what type a variable, parameter, or return value should be.
25 min•By Priygop Team•Last updated: Feb 2026
Type Annotations
In TypeScript, you add a colon and a type after a variable name or parameter: let name: string = 'Alice'. This tells TypeScript that name must always be a string. If you try to assign a number to it, TypeScript will show an error. Type annotations are optional — TypeScript can often infer types automatically.
Basic Types
- string — Text: let name: string = 'Alice'
- number — Numbers: let age: number = 25
- boolean — True/false: let active: boolean = true
- any — Disables type checking (avoid): let x: any = 'anything'
- void — Function returns nothing: function log(): void { }
- null and undefined — Absence of value
- Type inference — TypeScript guesses the type from the value
Type Annotations Example
Example
// Variable annotations
let name: string = "Alice";
let age: number = 25;
let isStudent: boolean = true;
// Function parameter and return type annotations
function greet(person: string): string {
return "Hello, " + person + "!";
}
function add(a: number, b: number): number {
return a + b;
}
function logMessage(msg: string): void {
console.log(msg);
// No return value (void)
}
// Type inference — TypeScript figures out the type
let city = "Mumbai"; // TypeScript infers: string
let count = 42; // TypeScript infers: number
// Arrays with types
let fruits: string[] = ["Apple", "Banana", "Mango"];
let scores: number[] = [95, 87, 92, 78];
console.log(greet(name));
console.log(add(10, 5));
console.log(fruits[0]);Try It Yourself: Type Annotations
Try It Yourself: Type AnnotationsJavaScript
JavaScript Editor
✓ ValidTab = 2 spaces
JavaScript|32 lines|862 chars|✓ Valid syntax
UTF-8