Classes Implement Interface Contracts

Declare capability surfaces with interfaces and make classes opt in via implements, so missing members or wrong signatures fail at compile time.

TypescriptData Integrity

Code

typescriptsnippet
38 lines
type Category = 'food' | 'travel' | 'software';

interface Expense {
  id: string;
  cents: number;
  category: Category;
}

// 接口声明能力面:实现类必须提供全部成员,签名不匹配就编译报错
interface ExpenseRepository {
  save(expense: Expense): Expense;
  findByCategory(category: Category): Expense[];
}

// implements:漏方法、拼错方法名、返回类型不符都会被编译器拦下
class InMemoryExpenseRepository implements ExpenseRepository {
  private items: Expense[] = [];

  save(expense: Expense): Expense {
    this.items.push(expense);
    return expense;
  }

  findByCategory(category: Category): Expense[] {
    return this.items.filter((item) => item.category === category);
  }
}

// 调用方只依赖接口类型,不依赖具体实现
const repo: ExpenseRepository = new InMemoryExpenseRepository();

repo.save({ id: 'e-1', cents: 1250, category: 'food' });
repo.save({ id: 'e-2', cents: 4200, category: 'travel' });
repo.save({ id: 'e-3', cents: 9900, category: 'software' });

const food = repo.findByCategory('food');
console.log('food expenses:', food.map((e) => `${e.id}@${e.cents}`));
console.log('travel count:', repo.findByCategory('travel').length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

food expenses: [ 'e-1@1250' ]
travel count: 1

The contract surface

ExpenseRepository declares save and findByCategory signatures; InMemoryExpenseRepository attaches implements ExpenseRepository, so a missing method, a misspelled name, or a mismatched return type fails compilation rather than at the first call.

Program to the interface

The repo constant is typed ExpenseRepository, not the concrete class — callers see only the contract, and swapping implementations needs no call-site changes.

Running result

Three expenses go in under food/travel/software; the food query prints e-1@1250 and travel count prints 1, demonstrating both repository methods through the interface type.

Interactive Tools for This Topic

FAQ

What does implements add over TypeScript's structural typing?
An explicit compile-time check that the class truly satisfies the interface — missing or mistyped members error at the class, not at a distant call site.
Why is the repo variable typed as the interface?
So callers depend only on the contract; replacing the in-memory implementation with another ExpenseRepository needs no call-site edits.