TypeScript — Interfaces
Basic interface
interface Person {
name: string;
age: number;
email?: string; // Optional
}
const alice: Person = {
name: "Alice",
age: 30
};
// alice.email is string | undefined
Readonly properties
interface Config {
readonly apiUrl: string;
readonly timeout: number;
}
const config: Config = {
apiUrl: "https://api.example.com",
timeout: 5000
};
// config.apiUrl = "other"; // Error: readonly
Extending interfaces
interface Animal {
name: string;
age: number;
}
interface Dog extends Animal {
breed: string;
bark(): void;
}
const rex: Dog = {
name: "Rex",
age: 5,
breed: "German Shepherd",
bark() {
console.log("Woof!");
}
};
// Multiple inheritance
interface Printable {
print(): void;
}
interface Loggable {
log(): void;
}
interface Document extends Printable, Loggable {
title: string;
content: string;
}
Index signatures
interface StringMap {
[key: string]: string;
}
const translations: StringMap = {
hello: "Hello",
goodbye: "Goodbye"
};
// Interface with number index
interface NumberMap {
[index: number]: string;
}
const items: NumberMap = ["a", "b", "c"];
Function types in interfaces
interface MathOps {
add(a: number, b: number): number;
subtract(a: number, b: number): number;
}
const math: MathOps = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
// Callable interface
interface Greeter {
(name: string): string;
}
const greet: Greeter = (name) => `Hello, ${name}!`;
Interface vs type
// Interface: can be extended, merged
interface User {
name: string;
}
interface User {
age: number;
}
// User now has both name and age
// Type: more flexible, can't be merged
type Point = {
x: number;
y: number;
};
// Type: union types
type ID = string | number;
// Type: mapped types
type Readonly<T> = {
readonly [K in keyof T]: T[K];
};
// Use interface for: objects, classes, extendable contracts
// Use type for: unions, intersections, mapped types, primitives
Declaration merging
// Interface merging (intentional)
interface Window {
myCustomProp: string;
}
// Built-in Window now has myCustomProp
// Module augmentation
declare module "some-lib" {
interface Config {
customOption: boolean;
}
}
Generic interfaces
interface Repository<T> {
findById(id: string): Promise<T>;
findAll(): Promise<T[]>;
save(entity: T): Promise<T>;
delete(id: string): Promise<void>;
}
interface User {
id: string;
name: string;
email: string;
}
class UserRepository implements Repository<User> {
async findById(id: string): Promise<User> {
return { id, name: "Alice", email: "alice@example.com" };
}
async findAll(): Promise<User[]> {
return [];
}
async save(user: User): Promise<User> {
return user;
}
async delete(id: string): Promise<void> {
console.log(`Deleted ${id}`);
}
}
Utility types with interfaces
interface User {
name: string;
age: number;
email: string;
}
// Partial: all optional
type PartialUser = Partial<User>;
// Required: all required
type RequiredUser = Required<User>;
// Pick: select properties
type UserBasic = Pick<User, "name" | "email">;
// Omit: exclude properties
type UserWithoutEmail = Omit<User, "email">;
// Record
type UserMap = Record<string, User>;
Best practices
- Use interfaces for object shapes and class contracts
- Use
readonlyfor immutable data - Prefer interfaces for public APIs (extendable)
- Use type for unions and complex type operations
- Keep interfaces small and focused
Mini Practice
Write TypeScript code that:
- Defines an
ApiResponse<T>interface with generic data - Extends a base interface with additional properties
- Uses index signatures for a dynamic object
- Creates a class that implements an interface
Up Next
In the next lesson, you'll learn about Classes — OOP in TypeScript.
Related Topics
Frequently Asked Questions about Interfaces
What is Interfaces in TypeScript?
Interfaces is a fundamental concept in TypeScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Interfaces?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Interfaces.
Why is Interfaces important in TypeScript?
Interfaces is essential for TypeScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.