TypeScript Essentials
Dashboard
Topic 2/10
Home β€Ί Angular β€Ί TypeScript Essentials

πŸ“˜ 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.

types.ts TypeScript
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.

models.ts TypeScript
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.

person.ts TypeScript
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.

generics.ts TypeScript
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.

Note: Angular relies heavily on TypeScript decorators to define metadata for components, services, directives, and pipes.