Skip to content

Instantly share code, notes, and snippets.

@notgiorgi
Created August 1, 2017 08:37
Show Gist options
  • Save notgiorgi/687b4487ec4b0e930638083939acffa7 to your computer and use it in GitHub Desktop.
Save notgiorgi/687b4487ec4b0e930638083939acffa7 to your computer and use it in GitHub Desktop.
interface PaymentPattern<T> {
CreditCard: (card: CreditCardPayment) => T;
Cash: (cash: CashPayment) => T;
}
interface PaymentMatcher {
match<T>(p: PaymentPattern<T>): T;
}
abstract class Payment implements PaymentMatcher {
constructor(public readonly amount: number) {}
abstract match<T>(p: PaymentPattern<T>): T;
}
class CreditCardPayment extends Payment {
constructor(amount: number, public readonly fee: number) {
super(amount);
}
match<T>(p: PaymentPattern<T>): T {
return p.CreditCard(this);
}
}
class CashPayment extends Payment {
constructor(amount: number, public readonly discount: number) {
super(amount);
}
match<T>(p: PaymentPattern<T>): T {
return p.Cash(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment