Interfaces
Interfaces define the shape of objects — what properties and methods they must have. They are the primary way to define contracts in TypeScript and are fundamental to writing clean, maintainable code.
40 min•By Priygop Team•Last updated: Feb 2026
Interface Fundamentals
- Interface declaration — interface User { name: string; age: number; }. Defines required properties and their types
- Optional properties — email?: string means the property may or may not exist. Use for optional configuration
- Readonly properties — readonly id: number cannot be reassigned after initialization. Like const for object properties
- Method signatures — greet(name: string): string defines a method that must be implemented
- Index signatures — [key: string]: unknown allows additional dynamic properties alongside known properties
- Extending interfaces — interface Admin extends User { role: string; }. Inheritance for adding new properties
Interface Code Examples
Example
// Basic interface
interface User {
readonly id: number; // Cannot change after creation
name: string;
email: string;
age?: number; // Optional
isActive: boolean;
}
const user: User = {
id: 1,
name: "Alice",
email: "alice@example.com",
isActive: true
// age is optional, so we can omit it
};
// user.id = 2; // Error: readonly property
// Extending interfaces
interface Employee extends User {
department: string;
salary: number;
startDate: Date;
}
// Multiple inheritance
interface Manager extends Employee {
team: Employee[];
budget: number;
}
// Interface for functions
interface SearchFunction {
(query: string, limit?: number): Promise<User[]>;
}
const searchUsers: SearchFunction = async (query, limit = 10) => {
// Implementation...
return [];
};
// Index signatures for dynamic keys
interface TranslationMap {
[locale: string]: string;
}
const greetings: TranslationMap = {
en: "Hello",
es: "Hola",
fr: "Bonjour",
de: "Hallo"
};
// Interface merging (declaration merging)
interface Config { apiUrl: string; }
interface Config { timeout: number; }
// Config now has BOTH apiUrl AND timeout — interfaces merge!