Defining Interfaces
In this page:
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
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
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
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
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
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: