Basic Types & Annotations
TypeScript adds static type annotations to JavaScript. You tell TypeScript what type each variable, parameter, and return value should be — and it catches mismatches before your code runs.
Catches bugs at compile time instead of runtime. Provides IDE autocomplete and documentation. Makes large codebases maintainable. Required in most modern React/Next.js projects.
In any TypeScript file (.ts or .tsx). Type annotations are optional but recommended everywhere. TypeScript can infer many types automatically.
Add : type after variable names, parameters, and function signatures. TypeScript infers types when possible — only annotate when inference isn't clear.
Code Examples
#1Core type annotations
// TypeScript infers types automatically — you don't always need to annotatelet name = "Ali"; // inferred as stringlet age = 25; // inferred as numberlet active = true; // inferred as boolean// Explicit annotationslet username: string = "Ali";let score: number = 100;let isLoggedIn: boolean = false;let data: null = null;let x: undefined = undefined;// Arrayslet scores: number[] = [90, 85, 92];let names: string[] = ["Ali", "Ahmed"];let mixed: (string | number)[] = ["Ali", 25]; // union type in array// Tuple — fixed length array with specific types at each positionlet point: [number, number] = [10, 20];let person: [string, number] = ["Ali", 25];// any — escape hatch, avoid!let anything: any = "could be anything";anything = 42; // no error — any allows thisanything.foo.bar; // no error — TypeScript gives up on checking// unknown — safer than anylet value: unknown = getData();if (typeof value === "string") {console.log(value.toUpperCase()); // ✅ must check type first}// void — function that returns nothingfunction logMessage(msg: string): void {console.log(msg);// no return statement needed}// never — function that NEVER returns (throws or infinite loop)function throwError(message: string): never {throw new Error(message);}
Practice This Concept
Open the playground, paste any example, and experiment. The best way to learn is by breaking things.
Open in Playground