Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Sum Types to Model Data
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
You can’t perform that action at this time.