Created
November 1, 2021 18:16
-
-
Save manzanit0/2c71bfa404e7bb4760914124d9d277e2 to your computer and use it in GitHub Desktop.
Lightweight polymorphism in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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