我想从函数中返回一个有区别的联合类型 - 它与类型推断冲突 - 我应该如何更改我的代码以便getKeyA返回KeyA变为Key?
type KeyA = {keyString:string}
type KeyB = {keyInt:int}
type Key = KeyA | KeyB
let getKeyA id =
{keyString="123"}
let getKeyB id =
{keyInt=2}
let getKey (id) :Key =
match id with
| 1 -> getKeyA id
| _ -> getKeyB id
答案 0 :(得分:4)
简而言之:我不知道您提供的大多数部分的定义,但要返回Key
类型的内容,您必须在此示例中使用KeyA
或KeyB
试试这个:
type Key = KeyA of KeyA | KeyB of KeyB
let getKey id : Key =
match id with
| 1 -> KeyA (getKeyA id)
| _ -> KeyB (getKeyB id)
或者这看起来更适合你
type KeyA = {keyString:string}
type KeyB = {keyInt:int}
type Key = KeyA of KeyA | KeyB of KeyB
let getKeyA id =
{ keyString="123" }
|> KeyA
let getKeyB id =
{ keyInt=2 }
|> KeyB
let getKey id : Key =
match id with
| 1 -> getKeyA id
| _ -> getKeyB id
您可能会注意到,您只将string
或int
包装到记录中 - 如果它只是一种类型/值,或者如果您可以使用元组,我会删除其他记录:< / p>
type Key = KeyA of string | KeyB of int
let getKeyA id = KeyA "123"
let getKeyB id = KeyB 2
let getKey id : Key =
match id with
| 1 -> getKeyA id
| _ -> getKeyB id