Created
February 23, 2020 20:11
-
-
Save rahulpnath/196996a8502b7109bd98816c73a7f26c to your computer and use it in GitHub Desktop.
Using Sum Types to Model Data
This file contains 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
import * as React from "react"; | |
import { render } from "react-dom"; | |
const styles = { | |
margin: "10px" | |
}; | |
export type PaymentOption = FullPaymentOption | PartPaymentOption; | |
export interface FullPaymentOption { | |
type: "full"; | |
totalRental: number; | |
payNow: number; | |
refundableBond: number; | |
} | |
export interface PartPaymentOption { | |
type: "partial"; | |
totalRental: number; | |
payNow: number; | |
refundableBond: number; | |
balance: number; | |
balanceSurcharge?: number; | |
payLater: number; | |
} | |
const FullPaymentUI = ({ payment }: { payment: FullPaymentOption }) => ( | |
<div style={styles}> | |
<strong>Full Payment</strong> | |
<div>Total amount {payment.totalRental} </div> | |
<div>Pay now {payment.payNow} </div> | |
<div>Refundable bond {payment.refundableBond} </div> | |
</div> | |
); | |
const PartPaymentUI = ({ payment }: { payment: PartPaymentOption }) => ( | |
<div style={styles}> | |
<strong>Partial Payment</strong> | |
<div>Total amount {payment.totalRental} </div> | |
<div>Pay now {payment.payNow} </div> | |
<div>Refundable bond {payment.refundableBond} </div> | |
<div>Balance {payment.balance} </div> | |
<div>Balance Surcharge {payment.balanceSurcharge} </div> | |
<div>Pay Later {payment.payLater} </div> | |
</div> | |
); | |
const fullPayment: FullPaymentOption = { | |
type: "full", | |
payNow: 1000, | |
totalRental: 1000, | |
refundableBond: 5000 | |
}; | |
const partPayment: PartPaymentOption = { | |
type: "partial", | |
payNow: 200, | |
totalRental: 1000, | |
refundableBond: 5000, | |
balance: 800, | |
balanceSurcharge: 20, | |
payLater: 820 | |
}; | |
class App extends React.Component { | |
private paymentOptions = [fullPayment, partPayment]; | |
render() { | |
return ( | |
<div> | |
{this.paymentOptions.map(paymentOption => { | |
switch (paymentOption.type) { | |
case "full": | |
return <FullPaymentUI payment={paymentOption} />; | |
case "partial": | |
return <PartPaymentUI payment={paymentOption} />; | |
} | |
return <></>; | |
})} | |
</div> | |
); | |
} | |
} | |
render(<App />, document.getElementById("root")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment