typescript - 像 F# 中的包装类型
问题描述
在 F# 中,我可以像这样包装原始类型string
:
type CustomerId = CustomerId of string
let id: CustomerId = CustomerId("123")
如果我使用的是这样的int
而不是:CustomerId("123")
let id: CustomerId = 123
我收到此错误:
This expression was expected to have type
'CustomerId'
but here has type
'int'
现在我正在尝试以这种方式在 TypeScript 中做类似的事情:
type CustomerId = string
const id: CustomerId = '123'
首先,如果我分配 a而不是 a to ,我不能分配CustomerId('123')
给第二个,TypeScript 只会给我这个错误:id
number
string
id
Type '123' is not assignable to type 'string'.
与 F# 实现相比,我可以使用 TypeScript 获得最接近的(不使用类和接口)是什么?
解决方案
您可以使用以下方法非常接近:
type CustomerId = { CustomerId: string}
在 TS 中,我们无法通过仅用 a 包装原始值来构建案例,CustomerId
但您可以创建一个简单的辅助方法来为您完成它:
const customerId = (id: string): CustomerId => ({ CustomerId: id })
const a = customerId("123")
// a = CustomerId
如果你在构造函数中使用了错误的类型,TS 会给你类型错误
const a = customerId(7)
// ^
// Argument of type '7' is not assignable to parameter of type 'string'
推荐阅读
- android - Android Studio HiAI 引擎集成流程
- elasticsearch - 弹性搜索从搜索结果中排除嵌套元素,通过 id 获取元素
- rust - rust 和 python 中打印的不同输出
- ios - 使用 CIAztecCodeGenerator/CIQRCodeGenerator 时捕获 CIFilter.outputImage 的错误
- node.js - 如何解决错误“SyntaxError: Unexpected token '?'”
- python - CQLSH ImportError:无法导入名称 ensure_str
- python - 如何在列表中保存 50 张图像
- tensorflow - 为什么 Keras LSTM 中的准确率保持为零,而其他指标在训练时有所提高?
- python - 当我向集合中添加相对路径字符串时,为什么反斜杠的数量会增加?
- python - 如何在Python中用“OR”为列分配新值