Concept Explanation
Before you can describe complex objects, you need the basic "colors" on TypeScript's palette. Every value you annotate uses one of these primitive building blocks — and combining them is how you describe anything.
The magic character is the colon. After a variable name, : type tells TypeScript exactly what's allowed to live there.
Syntax or Core Structure
let age: number = 30;
let name: string = "Ada";
let isAdmin: boolean = true;
let scores: number[] = [90, 85, 100]; // an array of numbers
let pair: [string, number] = ["Ada", 30]; // a fixed tuple
let role: "admin" | "user" = "admin"; // literal union — only these two
Three special types you must know:
let anything: any; // ❌ turns OFF type checking — avoid
let mystery: unknown; // ✅ safe unknown — must check before use
function log(): void {} // returns nothing
Common Mistakes
- Reaching for any:
anysilences the compiler entirely. Preferunknownand narrow it. - Over-Annotating:
let x: number = 5is redundant — TS infersnumber. Annotate function params and return types; let inference handle the rest. - Confusing [] with tuple:
number[]is any length;[number, number]is exactly two.
Best Practices
- Let Inference Work: Annotate boundaries (function signatures), not every local variable.
- Prefer Literal Unions:
"sm" | "md" | "lg"beats a loosestringfor fixed options. - unknown over any: When a type is genuinely unknown, use
unknownso TS forces you to check.
Practice Exercises
- The Palette: Declare one variable of each: number, string, boolean, and a string array.
- The Tuple: Create a tuple type
Pointof two numbers and assign one. - The Union: Write
type Size = "small" | "medium" | "large"and try assigning an invalid value to see the error.