TypeScript adds type annotations to JavaScript. This tells the compiler what kind of data a variable should hold.
Primitive Types:
number- For numbers (integers, decimals, negative numbers)string- For text databoolean- For true/false valuesDate- For date and time values
Array Types:
string[]- Array of stringsnumber[]- Array of numbersboolean[]- Array of booleans
Type Safety: Once you declare a variable with a type, TypeScript prevents you from assigning values of different types:
let userId: number = 123;
userId = "456"; // ❌ Error! Can't assign string to number
let userName: string = "Sarah";
userName = 42; // ❌ Error! Can't assign number to string
Implicit Types: TypeScript can often figure out the type automatically from the value you assign:
// TypeScript infers these types automatically
let age = 25; // TypeScript knows this is number
let name = "Alex"; // TypeScript knows this is string
let isStudent = true; // TypeScript knows this is boolean
Special Types: TypeScript has some special types that don’t fit the basic categories:
null and undefined:
null- Explicitly represents “no value” or “empty”undefined- Variable is declared but hasn’t been assigned a value
any:
any- Turns off TypeScript’s type checking completely- Use sparingly - it defeats the purpose of TypeScript
- Useful when working with external libraries or unknown data
never:
never- Represents values that never occur- Common in functions that always throw errors or never return