Interfaces
Defining reusable object shapes
Introduction
In this lesson, you'll learn about interfaces in TypeScript. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with defining reusable object shapes.
TypeScript has its own approach to defining reusable object shapes, which we'll explore step by step.
The TypeScript Way
Let's see how TypeScript handles this concept. Here's a typical example:
// TypeScript interfaces define object shapes
interface User {
name: string;
age: number;
email?: string;
}
const user1: User = { name: "Alice", age: 30 };
const user2: User = { name: "Bob", age: 25 };
function printUser(user: User): void {
console.log(user.name);
}
// All users must conform to User interfaceComparing to JavaScript
Here's how you might have written similar code in JavaScript:
// JavaScript - no formal interfaces
// We just use objects that have the expected properties
const user1 = { name: "Alice", age: 30 };
const user2 = { name: "Bob", age: 25 };
function printUser(user) {
console.log(user.name);
}
// No way to ensure all users have same shapeYou may be used to different syntax or behavior.
Interfaces define contracts for object shapes
You may be used to different syntax or behavior.
Interfaces can be extended and merged
You may be used to different syntax or behavior.
Use interfaces for public API definitions
Step-by-Step Breakdown
1. Basic Interfaces
Interfaces define the shape that objects must have.
interface Point {
x: number;
y: number;
}
const origin: Point = { x: 0, y: 0 };2. Extending Interfaces
Interfaces can extend other interfaces to add properties.
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
bark(): void;
}
const dog: Dog = {
name: "Rex",
breed: "German Shepherd",
bark() { console.log("Woof!"); }
};3. Interface vs Type
Both can define object shapes, but interfaces can be extended and merged.
// Interface - can be extended
interface User {
name: string;
}
interface User {
age: number; // merged!
}
// Type alias - cannot be reopened
type Person = {
name: string;
};Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- Interfaces define contracts for object shapes
- Interfaces can be extended and merged
- Use interfaces for public API definitions
Key Takeaways
- Interfaces define object shapes as contracts
- Use extends to create interface hierarchies
- Interfaces can be merged (declaration merging)
- Prefer interfaces for object types, types for unions