Menu

3. TypeScript

Next.js Master Roadmap - IT Technology

This chapter introduces TypeScript fundamentals such as primitive types, interfaces, generics, and utility types, then progresses to advanced concepts including type guards, mapped types, and conditional types. Practical examples and explanations illustrate how to leverage TypeScript’s type system for safer, more maintainable code.

No MCQ questions available for this chapter.

3. TypeScript

TypeScript Fundamentals

3.1.1 Basic Types

TypeScript’s primitive types form the building blocks of any application. The language provides string, number, boolean, null, undefined, symbol, and bigint. These types can be combined to create more complex structures.

  • Arrays: Defined with string[] or the generic Array<string> syntax.
  • Tuples: Fixed‑length arrays where each position has a known type, e.g. [string, number].
  • Enums: Allow defining a set of named constants. Numeric enums start at 0 by default, while string enums require explicit initialization.
  • Any and Unknown: any disables type checking, whereas unknown requires narrowing before use.

Example:

const age: number = 25;
const tags: string[] = ['react', 'nextjs'];
const user: [string, number] = ['Alice', 30];

3.1.2 Interfaces

Interfaces describe the shape of objects. They are extensible and support declaration merging, meaning multiple declarations with the same name are automatically combined.

  • Basic syntax: interface User { name: string; }
  • Extension: interface Admin extends User { permissions: string[]; }
  • Optional properties: Marked with ? (e.g., error?: string).
  • Readonly: Prefixed with readonly to prevent reassignment.
  • Generics in interfaces: interface ApiResponse<T> { data: T; status: number; error?: string; }

Example:

interface ApiResponse<T> {
  data: T;
  status: number;
  error?: string;
}

3.1.3 Type Aliases

Type aliases create a name for any type, including unions, intersections, and tuples. Unlike interfaces, they cannot be extended with extends; instead, intersections (&) are used.

  • Union alias: type ID = string | number;
  • Object alias: type User = { name: string; age: number; }
  • Discriminated union: type Result<T, E> = { success: true; data: T } | { success: false; error: E };

3.1.4 Enums

Enums can be numeric (default) or string‑based. Const enums (const enum) inline their values at compile time, eliminating runtime overhead.

  • Numeric enum: enum Status { Pending = 0, Success = 1, Error = 2 }
  • String enum: enum Direction { Up = "UP", Down = "DOWN" }
  • Const enum: const enum LogLevel { Off, Error, Warn, Info, Debug }

Usage example:

function handle(status: Status) {
  if (status