首页 > 解决方案 > 如何在打字稿中创建不可分配的数字?

问题描述

在我们国家有两种货币,里亚尔和托曼,它们可以相互转换(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

标签: typescript

解决方案


这个可行,但这不是一个很好的解决方案!

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)

推荐阅读