Interface Definition
Problem
Objects are passed around with implicit structures, making it unclear what properties exist or what types they should have. Developers access non-existent properties, mistype field names, and pass wrong data types, all without any compile-time warnings. Refactoring becomes dangerous because there’s no way to track which code depends on specific object shapes.
Solution
Declare contracts for objects and functions using TypeScript interfaces or similar type systems. This documents expectations and enables compile-time verification that implementations match.
Example
interface User {
id: number;
name: string;
email: string;
isActive?: boolean;
}
function getUser(id: number): User {
return { id, name: 'John', email: 'john@example.com' };
}
Benefits
- Documents object shapes and function signatures, making code self-describing.
- Enables compile-time type checking to catch mismatches before runtime.
- Improves IDE support with autocomplete and inline documentation.
- Makes refactoring safer by tracking all uses of a given interface.
Tradeoffs
- Requires TypeScript or similar type system, adding build complexity.
- Can be verbose with boilerplate interface definitions for simple objects.
- May create friction when prototyping or working with dynamic data.
- Needs maintenance when API contracts change or evolve over time.