如何在F#中将类型声明为受约束的
f#
在 Nodejs 中,我可以声明如下内容(注意 productType )。这在 F# 中的 Record 或 struct 中可能吗?我不想使用类 - 我不认为我可以使用枚举,因为我想存储“S”或“G”
export interface Product {
_id?: string
sku: string
name: string
productType: 'S' | 'G' //S, G ( simple , grouped )
}
回答
您可以使用有区别的联合。
代码将如下所示:
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 }
- @KenTsu `option<string>` is harder to write than `string option` and also it's against [guideline](https://docs.microsoft.com/en-us/dotnet/fsharp/style-guide/formatting#use-prefix-syntax-for-generics-foot-in-preference-to-postfix-syntax-t-foo)