π TypeScript Essentials
TypeScript basics, types, interfaces, classes, generics, and decorators.
Why TypeScript for Angular?
TypeScript adds optional static typing, modern JavaScript features, and compile-time error checking. It drastically improves IDE autocompletion, refactoring, and code maintainability in large Angular codebases.
Basic Types & Type Annotations
TypeScript supports primitive types as well as advanced type constructs.
let username: string = 'Alice'; let age: number = 28; let isActive: boolean = true; let skills: string[] = ['Angular', 'RxJS', 'TypeScript']; // Union types let id: string | number = 101; // Enum definition enum Role { Admin, User, Guest } let currentRole: Role = Role.Admin;
Interfaces vs Type Aliases
Interfaces define object shapes and contracts for classes. Type aliases can also define object shapes, unions, and primitives.
export interface User { id: number; name: string; email: string; role?: string; // Optional property } export type Status = 'pending' | 'approved' | 'rejected';
Classes and Access Modifiers
TypeScript provides `public`, `private`, `protected`, and `readonly` access modifiers for object-oriented programming.
export class Person { private id: number; constructor(id: number, public name: string) { this.id = id; } public getId(): number { return this.id; } }
Generics
Generics enable creating reusable components and functions that work across a variety of types while retaining full type safety.
function identity<T>(arg: T): T { return arg; } let num = identity<number>(42); let str = identity<string>('Hello');
TypeScript Decorators
Decorators (`@Component`, `@Injectable`, `@Input`) are metadata functions that annotate and modify classes and class members at design time.