Advertisement
Advanced TypeScript, Structural Typing & Duck Typing

How would you leverage structural typing to design a flexible 'partial dependency injection' interface for testing, accepting any object with the needed shape rather than requiring a specific concrete class?

Short answer

Define a narrow interface describing ONLY the specific methods/properties your code actually depends on (rather than depending on a full concrete class or library type) — thanks to structural typing, ANY object satisfying that minimal shape (a real service, an in-memory fake, or…

Save TypeScript mock interview
Advertisement
AModel answer
Define a narrow interface describing ONLY the specific methods/properties your code actually depends on (rather than depending on a full concrete class or library type) — thanks to structural typing, ANY object satisfying that minimal shape (a real service, an in-memory fake, or a test double) can be passed in without needing formal inheritance or 'implements' declarations.
interface Logger { log(message: string): void; }
class ProductionLogger implements Logger { log(m: string) { /* sends to real service */ } }
class FakeLogger implements Logger { logs: string[] = []; log(m: string) { this.logs.push(m); } }

function doWork(logger: Logger) { logger.log('working...'); }
doWork(new FakeLogger()); // trivially swappable in tests, thanks to structural typing
Real-world example
Designing highly testable code by depending on minimal, narrowly-scoped interfaces rather than concrete implementation classes.
Likely follow-ups
  • How does this structural-typing-driven design relate to the Dependency Inversion Principle from SOLID?
Related topics