Lesson 7 +10 XP

Interface Fundamentals & Optional Properties

Interfaces & Optional Properties

An interface in TypeScript defines the structure of an object. It acts as a contract that objects must fulfill.

Defining an Interface

interface User {
  id: number;
  name: string;
  email: string;
}

const alice: User = {
  id: 1,
  name: "Alice",
  email: "alice@example.com"
};

Optional Properties (?)

Properties can be marked as optional using a question mark (?). Optional properties can be present or omitted (undefined).

interface UserConfig {
  username: string;
  theme?: string; // Optional property
  age?: number;   // Optional property
}

const config1: UserConfig = { username: "coder123" }; // Valid
const config2: UserConfig = { username: "coder123", theme: "dark" }; // Valid

TL;DR

  • Interfaces define object shapes.
  • Use ? after property names to mark them as optional.
  • Missing required properties trigger compile errors.