类型预测仅在管道函数中有效

Type predictions work only within pipe function

我在我的项目中使用 monocle-ts (https://github.com/gcanti/monocle-ts) 库。 我有以下代码

import {id, prop} from 'monocle-ts/lib/Lens'
import {pipe} from 'fp-ts/function'

type State = {a: string, b: string}
const stateLens = id<State>()
const aLens = pipe(stateLens, prop('a'))

^ 这段代码工作得很好,类型系统不允许我传递既不是 'a' 也不是 'b' 的字符串。 但是,如果我试图以其他方式编写相同的代码:

const aLens = prop('a')(stateLens)

我遇到一个错误:Argument of type 'string' is not assignable to parameter of type 'never' prop 函数的类型定义如下所示:

declare const prop: <A, P extends keyof A>(prop: P) => <S>(sa: Lens<S, A>) => Lens<S, A[P]>

我猜想通过使用管道式打字稿能够以某种方式推断出所有通用参数,而常规 prop(...)(...) 调用

并非如此

您尝试的替代表示法是一个 two-step 过程,它首先使用 prop('a') 创建一个 lambda 函数,然后立即使用 ...(stateLens) 调用它。 prop() 函数只接收键名 'a',但无法确定它所属的对象,因为它只有字符串参数 'a' 可以使用。因此,在 prop 的类型定义中,类型 A 将被解析为 never,因为它未分配且无法推断。

我没有测试这个,但你可能可以通过手动传递像

这样的类型来做同样的事情
prop<State, 'a'>('a')(stateLens)

但这正是 pipe 所做的,因为它从第一个参数接收 State 类型,我想你会同意在这种情况下使用 pipe 看起来更好.

所以,你是对的,pipe 能够推断出正确的类型并将其传递给 prop