TypeScript Interfaces - The Complete Guide
Master TypeScript interfaces, extending interfaces, interface merging, and interface vs type alias!
Introduction
Interfaces are a powerful way to define types for objects and more! Let's master them!
What You Will Learn
- Interface basics
- Extending interfaces
- Optional and readonly properties
- Interface vs type alias
Prerequisites
What is an Interface?
An interface defines the shape of an object!
interface User {
id: number;
name: string;
email: string;
isAdmin?: boolean;
}
const user: User = {
id: 1,
name: "John",
email: "j@j.com",
};
Extending Interfaces!
Reuse interfaces by extending them!
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
id: number;
position: string;
}
const employee: Employee = {
name: "John",
age: 30,
id: 1,
position: "Developer",
};
Optional & Readonly Properties!
interface User {
readonly id: number;
name: string;
email: string;
phone?: string;
}
Interface vs Type Alias!
Use interface for object types! Use type for other types (unions, tuples)!
interface User {
name: string;
}
type ID = string | number;
type Coordinate = [number, number];
Interface Merging!
Interfaces automatically merge!
interface User {
name: string;
}
interface User {
age: number;
}
// Combined: { name: string; age: number }
Best Practices
- Use interfaces for object shapes: Most common case!
- Extend interfaces: Reuse code!
- Name interfaces clearly:
User,Product, etc.
Summary
Interfaces are great for defining reusable object types!
Related Articles
Previous Tutorial
← Objects
Next Tutorial
Let's learn type aliases! → Type Aliases