Skip to content

Instantly share code, notes, and snippets.

@manzanit0
Created November 1, 2021 18:16
Show Gist options
  • Save manzanit0/2c71bfa404e7bb4760914124d9d277e2 to your computer and use it in GitHub Desktop.
Save manzanit0/2c71bfa404e7bb4760914124d9d277e2 to your computer and use it in GitHub Desktop.
Lightweight polymorphism in Typescript
interface UseCase {
isValid(): boolean;
handle(): void;
}
const runUsecase = (usecase: UseCase) => {
if (usecase.isValid()) {
usecase.handle();
}
};
const goodUseCase = {
handle: () => 42,
isValid: () => true,
};
const badUseCase = {
handle: () => 42,
isValid: () => "noop",
};
runUsecase(goodUseCase); // compiles
runUsecase(badUseCase); // Doesn't compile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment