在我国,有两种货币,里亚尔和托曼,可以相互转换(1 two = 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发布于 2020-08-18 22:46:26
这个可行,但这不是一个很好的解决方案!
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)发布于 2020-08-18 23:41:16
类型记录有构造类型,所以如果希望两种类型彼此不可分配,那么它们必须具有不兼容的结构。我们可以通过赋予类型额外的属性来区分它们来实现这一点;这些属性在运行时并不真正存在,因此不存在性能损失。
注意,在赋值的位置需要一个类似于5 as toman的类型断言。
type toman = number & { __toman: toman }
type rial = number & { __rial: rial }
function x(r: rial): void {
console.log(r)
}
const t = 5 as toman
x(t) // error: property '__rial' is missing发布于 2020-08-18 22:47:21
我看不出有什么原因,因为两者都有相同的类型:数字。但是,您可以这样做:
type Currency<PropertyName extends string> = {
[key in PropertyName]: number
}
function x(r: Currency<'rial'>): void {
console.log(r)
}
const t = {toman: 5} // change to { rial: 5 } to fix the ts error below
x(t) // You you get an errorhttps://stackoverflow.com/questions/63477131
复制相似问题