首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在打字本中创建不可分配的数字?

问如何在打字本中创建不可分配的数字?
EN

Stack Overflow用户
提问于 2020-08-18 21:51:07
回答 3查看 63关注 0票数 0

在我国,有两种货币,里亚尔和托曼,可以相互转换(1 two = 10里亚尔),我想为每种货币创建一个特定的类型,即不可转让的货币。我不想失去任何性能(例如,使用对象而不是数字)

示例代码:

代码语言:javascript
复制
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
EN

回答 3

Stack Overflow用户

发布于 2020-08-18 22:46:26

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

代码语言:javascript
复制
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)
票数 1
EN

Stack Overflow用户

发布于 2020-08-18 23:41:16

类型记录有构造类型,所以如果希望两种类型彼此不可分配,那么它们必须具有不兼容的结构。我们可以通过赋予类型额外的属性来区分它们来实现这一点;这些属性在运行时并不真正存在,因此不存在性能损失。

注意,在赋值的位置需要一个类似于5 as toman的类型断言。

代码语言:javascript
复制
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

操场连接

票数 1
EN

Stack Overflow用户

发布于 2020-08-18 22:47:21

我看不出有什么原因,因为两者都有相同的类型:数字。但是,您可以这样做:

代码语言:javascript
复制
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 error
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63477131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档