【问题标题】:Is there a global option to enable Dinero.js strict currency format checking?是否有启用 Dinero.js 严格货币格式检查的全局选项?
【发布时间】:2022-11-08 15:27:18
【问题描述】:
使用最新的 Dinero,在我最近负责的代码库中,他们编写“usd”的方式缺乏标准。结果,会发生这种情况:
Dinero({
currency: 'usd' as 'USD',
amount: 1
}).add(Dinero({
currency: 'USD',
amount: 1,
}))
抛出You must provide a Dinero instance with the same currency。对于 Dinero,'usd' 和 'USD' 看起来不是同一种货币。
当提供错误的货币时,有没有办法让 Dinero 抛出?小写的usd 可能是错误的,因为在DefinitelyTyped 中货币类型仅包括USD。
如果不抛出,那么至少会自动将其转换为大写。
【问题讨论】:
标签:
javascript
typescript
dinero.js
【解决方案1】:
没有这样的选项,并且在撰写本文时不在计划中(https://github.com/dinerojs/dinero.js/issues/637)。
解决方案可能是限制从 eslint 中的“dinero.js”导入
"rules": {
"no-restricted-imports": ["error", {
"paths": [{
"name": "dinero.js",
"message": "please import dinero from utils/money"
}]
}]
}
...
export const Dinero = (...[opts]: Parameters<typeof DineroOriginal>) => {
if (opts?.currency && opts.currency.toUpperCase() !== opts.currency) {
// don't convert, but fail-fast
throw new Error(`Currency ${opts.currency} is not uppercase`);
}
return DineroOriginal(opts);
};