首页 > 解决方案 > 像 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 只会给我这个错误:idnumberstringid

Type '123' is not assignable to type 'string'.

与 F# 实现相比,我可以使用 TypeScript 获得最接近的(不使用类和接口)是什么?

标签: 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'

推荐阅读