TypeScript
Beginner
1 min read
Callable and Constructable Interfaces
Example
// Callable interface — function with properties
interface Logger {
(message: string): void; // call signature
level: "info" | "warn" | "error";
prefix: string;
}
function createLogger(prefix: string): Logger {
const log = (message: string) => {
console.log(`[${log.level.toUpperCase()}] ${log.prefix}: ${message}`);
};
log.level = "info";
log.prefix = prefix;
return log as Logger;
}
const appLog = createLogger("App");
appLog("Server started");
appLog.level = "warn";
appLog("Memory usage high");
// Construct signature — accept a class constructor
interface Constructable<T> {
new (id: number, name: string): T;
}
interface Entity {
id: number;
name: string;
}
function createEntity<T extends Entity>(
Ctor: Constructable<T>,
id: number,
name: string
): T {
return new Ctor(id, name);
}
class Product implements Entity {
constructor(public id: number, public name: string) {}
describe(): string { return `Product #${this.id}: ${this.name}`; }
}
const p = createEntity(Product, 101, "Widget");
console.log(p.describe());
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