如何在 F# 中将类型声明为受约束的

Mar*_*son 1 f#

在 Nodejs 中,我可以声明如下内容(注意 productType )。这在 F# 中的 Record 或 struct 中可能吗?我不想使用类 - 我不认为我可以使用枚举,因为我想存储“S”或“G”

export interface Product {
    _id?: string
    sku: string
    name: string
    productType: 'S' | 'G' //S, G ( simple , grouped )
}
Run Code Online (Sandbox Code Playgroud)

JL0*_*0PD 6

您可以使用有区别的联合

代码将如下所示:

type ProductType = Simple | Grouped

type Product =
    { Id   : string option // I don't know NodeJS, so I think that 'id?' is optional
      Sku  : string
      Name : string
      Type : ProductType }

Run Code Online (Sandbox Code Playgroud)

  • @KenTsu `option<string>` 比 `string option` 更难编写,而且它违反了[指南](https://docs.microsoft.com/en-us/dotnet/fsharp/style-guide/formatting#use -prefix-syntax-for-generics-foot-in-preference-to-postfix-syntax-t-foo) (3认同)