实现说明
值得阅读的是函数 format、makeFormatter,其余是驱动代码。
使用要点
- 演示输出是带标签的(
currencies:),每个操作都会留下自己的一行标注。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 format、makeFormatter。
签名一览:const format = (amount: number)
核心语句
return Object.assign(format, { currency });
代码示例
// A call signature describes a value that can be invoked like a function.
interface PriceFormatter {
(amount: number): string;
currency: string;
}
function makeFormatter(currency: string): PriceFormatter {
const format = (amount: number): string =>
new Intl.NumberFormat('en-US', {
style: 'currency',
currency,
minimumFractionDigits: 2,
}).format(amount);
return Object.assign(format, { currency });
}
const usd = makeFormatter('USD');
const eur = makeFormatter('EUR');
console.log(usd(19.5));
console.log(eur(19.5));
console.log('currencies:', usd.currency, eur.currency);