typescript - 如何在打字稿中创建不可分配的数字?
问题描述
在我们国家有两种货币,里亚尔和托曼,它们可以相互转换(1 托曼 = 10 里亚尔),我想为每种货币创建一个特定的类型,即不可分配。 我不想失去任何性能(例如使用对象而不是数字)
示例代码:
type toman = number
type rial = number
function x(r: rial): void {
console.log(r)
}
const t: toman = 5
x(t) // I want to get an error here, because toman is unassignable to rial
解决方案
这个可行,但这不是一个很好的解决方案!
interface Toman {
n: 'toman'
}
interface Rial {
n: 'rial'
}
type toman = Toman | number
type rial = Rial | number
function x(r: rial): void {
console.log(r)
}
const t = 5 as toman
x(t)
推荐阅读
- typeorm - TypeORM save() 方法是否也可以使用另一个键
- android - 如何在 Android 中将 Short[] 写入 wav 输出文件?
- html - Bootstrap CSS 未在示例页面上加载
- scala - 为什么 df 写入控制台格式不显示任何内容?
- python - 为什么 Python 不能分离复数的实部和虚部?
- c - 在 G-WAN 上安装 HTTP/3
- javascript - 不能为返回的每个元素创建一个 UUID?
- python - 推荐电影机器学习 X_train
- python - 在python中检测输入字符串中的所有数字的程序
- c# - Threadpool 不同的返回结果?