← Back to TypeScript Course | Chapter 4: Interfaces | Lesson 1 of 7

Defining Interfaces

An interface in TypeScript describes the shape of an object by specifying its properties and their types. Interfaces make object-based code easier to understand, check, and maintain.

Creating a Basic Interface

The interface keyword, followed by a name and a block of property definitions, defines the required shape an object must have to satisfy that interface. Any object assigned to a variable of that interface type must include every property the interface declares.

Example: Creating a Basic Interface

typescript
interface User {
  name: string;
  age: number;
}
const user: User = { name: "Farah", age: 27 };
console.log(user);

Multiple Properties

An interface can list as many properties as needed, each with its own type, to fully describe a complex object's shape. This gives a single, centralized definition that many parts of a codebase can reference instead of repeating the same object shape everywhere.

Example: Multiple Properties

typescript
interface Product {
  id: number;
  name: string;
  price: number;
  inStock: boolean;
}
const item: Product = { id: 1, name: "Mug", price: 8, inStock: true };
console.log(item);

Interfaces with Functions

Interfaces can describe function-typed properties just as easily as ordinary data properties, letting an object's shape include callable members like onClick: () => void. This is common for describing configuration objects that include callback handlers.

Example: Interfaces with Functions

typescript
interface Button {
  label: string;
  onClick: () => void;
}
const btn: Button = { label: "Save", onClick: () => console.log("Saved!") };
btn.onClick();

Interfaces with Arrays

An interface can describe the structure every object in an array must share, commonly paired with array typing like User[] where User is the interface. This ensures every single item in the collection, not just the array itself, is checked against the same shape.

Example: Interfaces with Arrays

typescript
interface User {
  name: string;
}
const users: User[] = [{ name: "Ken" }, { name: "Lia" }];
console.log(users);

Using Interfaces in Functions

Interfaces are frequently used directly as function parameter types, which documents exactly what shape of object a function expects to receive. This keeps function signatures self-explanatory and lets the compiler reject any object missing a required property.

Example: Using Interfaces in Functions

typescript
interface User {
  name: string;
  age: number;
}
function printUser(user: User) {
  console.log(`${user.name} (${user.age})`);
}
printUser({ name: "Omar", age: 22 });
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.