Skip to content
TypeScript Essentials

TypeScript Interfaces

Beginner Lesson 4 of 9

Interfaces define the structure of objects and provide type checking.

interface User {
name: string;
age: number;
email: string;
}
const user: User = {
name: "Alice",
age: 25,
email: "alice@example.com"
};
interface User {
name: string;
age: number;
email?: string; // Optional
}
const user: User = {
name: "Bob",
age: 30
// email is optional
};
interface Config {
readonly apiKey: string;
readonly baseUrl: string;
}
const config: Config = {
apiKey: "abc123",
baseUrl: "https://api.example.com"
};
// config.apiKey = "new"; // Error!
interface Calculator {
add(a: number, b: number): number;
subtract(a: number, b: number): number;
}
const calc: Calculator = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
employeeId: string;
department: string;
}
const employee: Employee = {
name: "Alice",
age: 25,
employeeId: "E123",
department: "Engineering"
};
interface StringMap {
[key: string]: string;
}
const headers: StringMap = {
"Content-Type": "application/json",
"Authorization": "Bearer token"
};
// Interfaces can be extended/merged
interface Animal {
name: string;
}
interface Animal {
age: number;
}
// Animal now has both name and age
// Types use intersection
type Pet = { name: string } & { age: number };

Continue to Classes →