TypeScript
Beginner
1 min read
Defining and Implementing Interfaces
Example
// Basic interface
interface User {
readonly id: number;
name: string;
email: string;
role?: "admin" | "user"; // optional
}
const alice: User = { id: 1, name: "Alice", email: "alice@example.com" };
// alice.id = 2; // Error: cannot assign to readonly property
// Interface for a function type
interface Formatter {
(value: string, locale: string): string;
}
const fmt: Formatter = (v, l) => v.toLocaleUpperCase(l);
// Implementing an interface in a class
interface Printable {
print(): void;
}
interface Serializable {
serialize(): string;
}
class Report implements Printable, Serializable {
constructor(private title: string, private body: string) {}
print(): void {
console.log(`=== ${this.title} ===\n${this.body}`);
}
serialize(): string {
return JSON.stringify({ title: this.title, body: this.body });
}
}
const report = new Report("Q1 Summary", "Revenue up 12%.");
report.print();
console.log(report.serialize());
// Index signatures
interface StringMap {
[key: string]: string;
}
const headers: StringMap = {
"Content-Type": "application/json",
"Authorization": "Bearer token123",
};
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript