Skip to content

Instantly share code, notes, and snippets.

@wangzuo
Last active June 12, 2018 06:14
Show Gist options
  • Save wangzuo/a42766f82cb49c7002d7f31fde0b1ddd to your computer and use it in GitHub Desktop.
Save wangzuo/a42766f82cb49c7002d7f31fde0b1ddd to your computer and use it in GitHub Desktop.
opaque types in flow
// @flow
export opaque type AccountBalance = number;
export opaque type AccountNumber: number = number;
export opaque type PaymentAmount: number = number;
// export opaque type AccountNumber = number;
// export opaque type PaymentAmount = number;
type Account = {
accountNumber: AccountNumber,
balance: AccountBalance,
};
function getAccount(accountNumber: AccountNumber): Account {
return { balance: 100, accountNumber };
}
export function validateAccountNumber(input: number): AccountNumber {
if (Math.floor(input) !== input) {
throw new Error('Invalid account number, must be an integer!');
}
return input;
}
export function validatePaymentAmount(input: number): PaymentAmount {
if (typeof input !== 'number' || isNaN(input)) {
throw new Error('PaymentAmount must be a valid number');
}
if (input <= 0) {
throw new Error("Can't pay zero or less!");
}
return input;
}
export function spend(accountNumber: AccountNumber, amount: PaymentAmount) {
const account = getAccount(accountNumber);
account.balance -= amount;
}
// @flow
import {
spend,
validateAccountNumber,
validatePaymentAmount,
type PaymentAmount,
} from './accounting';
type Request = {
body: {
accountNumber: number,
amount: number,
},
};
function calculateProfit(amount: PaymentAmount) {
return amount / 10;
}
export default function handleRequest(req: Request) {
const accountNumber = validateAccountNumber(req.body.accountNumber);
const amount = validatePaymentAmount(req.body.amount);
spend(accountNumber, amount);
// const { accountNumber, amount } = req.body;
// spend(amount, accountNumber);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment