Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// 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} === ${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", };
Result
Open