如果类型在之前的守卫中被缩小,F# 会缩小类型吗?
type FirstOption = bool option
type SecondOption = bool option
let foo first second =
match first with
| None -> false
| Some value when second.IsSome ->
// second is still Option<bool>
sencond // x this doesn't fly.
| Some value -> false
在这些情况下,我一直在使用 Optopn.map/map2/map3,但想知道我是否做错了什么。
对于 TypeScript,他们有基于控制流的分析:https://github.com/microsoft/TypeScript/issues/2388
最佳答案
您可以对两个选项进行模式匹配(很好地匹配两个选项的元组)
转换你的例子:
let foo first second =
match (first, second) with
| (None, _) -> false
| (Some _, Some s) -> s
| (Some x, None) -> false
可以简化为:
let foo first second =
match (first, second) with
| (Some _, Some s) -> s
| _ -> false
关于types - f# Narrow discriminated union in previous pattern matching guard(Control Flow Based Type Analysis),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63231237/