Skip to content
TypeScript Essentials

Lesson 1 of 6 · 20 min

x
1/6

Lesson position in the course — not completion. Use Mark Complete to track finished lessons (saved in this browser).

Types & Interfaces

TypeScript adds static type definitions to JavaScript, catching structural mismatches during development before code reaches runtime. Primitives include string, number, boolean, null, undefined, and symbol. You define complex object contracts using either type aliases or interface declarations.

While type aliases can represent primitive unions (type Status = 'pending' | 'success'), tuple types, and mapped types, interface declarations excel at defining object structures and support declaration merging across modules. Best practice is to use interface for public library APIs and extensible domain models, and type for unions, primitives, and complex type transformations.

Before
Untyped Plain JavaScript Object
1// Plain JS - Property typos only break at runtime2function printUser(user) {3  console.log(user.nam.toUpperCase()); // TypeError at runtime!4}
After
Typed Interface Declaration
1interface User {2  id: string;3  name: string;4  email?: string; // Optional property5}6 7function printUser(user: User): void {8  console.log(user.name.toUpperCase()); // Checked at compile-time9}

Exercise

Create a UserRole union type and a UserProfile interface with optional and readonly properties.

Check your understanding

  • What is declaration merging in TypeScript interfaces?Show answer

    Answer

    If multiple interface declarations share the same name in the same scope, TypeScript automatically merges their property definitions into a single interface.
  • When should you use a type alias instead of an interface?Show answer

    Answer

    Use a type alias when defining union types, tuple types, primitive aliases, or mapped types.

Progress is saved in this browser.

Next Lesson