TypeScript Essentials
Introduction to TypeScript
Introduction to TypeScript
Section titled “Introduction to TypeScript”TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.
Why TypeScript?
Section titled “Why TypeScript?”- Type Safety - Catch errors at compile time
- Better IDE Support - Autocomplete, refactoring, navigation
- Self-Documenting - Types serve as documentation
- Scalability - Easier to maintain large codebases
# Install TypeScriptnpm install -g typescript
# Initialize projecttsc --init
# Compile TypeScripttsc file.ts
# Watch modetsc --watchBasic Types
Section titled “Basic Types”// Primitiveslet name: string = "Alice";let age: number = 25;let isActive: boolean = true;
// Arrayslet numbers: number[] = [1, 2, 3];let names: Array<string> = ["Alice", "Bob"];
// Tuplelet tuple: [string, number] = ["Alice", 25];
// Any (avoid when possible)let anything: any = "could be anything";
// Unknown (safer than any)let unknown: unknown = 4;Type Inference
Section titled “Type Inference”// TypeScript infers the typelet message = "Hello"; // stringlet count = 42; // number
// No need to annotate when type is obviousconst user = { name: "Alice", age: 25}; // { name: string; age: number }Functions
Section titled “Functions”// Parameter and return typesfunction greet(name: string): string { return `Hello, ${name}!`;}
// Optional parametersfunction greet(name: string, greeting?: string): string { return `${greeting || "Hello"}, ${name}!`;}
// Default parametersfunction greet(name: string, greeting: string = "Hello"): string { return `${greeting}, ${name}!`;}
// Arrow functionsconst add = (a: number, b: number): number => a + b;Next Steps
Section titled “Next Steps”Continue to TypeScript Setup →
Tutorials