Interfaces
TypeScript interfaces as contracts for classes and dependency boundaries.
16 minLevel 12 of 20
Interfaces as contracts
A TypeScript interface describes a shape without implementation. Classes implement it. This is the language feature behind Nest ports and DIP.
implements
interface UserRepo {
findById(id: string): { id: string; name: string } | null;
}
class MemoryUserRepo implements UserRepo {
findById(id: string) { return { id, name: "Grace" }; }
}
class GetUser {
constructor(private users: UserRepo) {}
exec(id: string) { return this.users.findById(id); }
}
console.log(new GetUser(new MemoryUserRepo()).exec("1"));Interfaces vs types
For object contracts, interface and type often interchange. Interfaces can be merged and read clearly for OOP. Prefer interfaces for class contracts in Nest codebases.
Structural typing
interface Logger { log(m: string): void; }
const logger: Logger = { log: (m) => console.log(m) };
logger.log("structurally compatible");Token boundaries
When Nest cannot use a class type as token (interfaces erase at runtime), use string/symbol tokens with @Inject(). Still design with interfaces in TypeScript.
Conceptual token
interface Clock { now(): number; }
class SystemClock implements Clock { now() { return Date.now(); } }
class Service {
constructor(private clock: Clock) {}
stamp() { return this.clock.now(); }
}
console.log(typeof new Service(new SystemClock()).stamp());Check your understanding
5 questionsQuestion 1 of 5
Score: 0
Multiple choice