从 Typescript 中的 promise 推断返回值

Joo*_*zty 5 typescript

我有一个非常简单的函数,它接受两个参数——节点对象异步函数,它们以某种方式处理给定的节点并返回处理过的节点,它可以是任何东西。

我想让它通用并从异步函数推断类型。这是我的尝试,但 TS 在抱怨,我真的不明白为什么。

// ensure that callback is of a correct type
type NodeCallback<H> = H extends (node: Node) => Promise<infer R> ? (node: Node) => Promise<R> : never

// retrieve return value
type NodeCallbackReturnValue<H> = H extends (node: Node) => Promise<infer R> ? R : never


const myAsyncFunction = <_, C>(node: Node, cb: NodeCallback<C>) => {
  return cb(node)
}


myAsyncFunction(document, (node: Node) => Promise.resolve(node.nodeType))
Run Code Online (Sandbox Code Playgroud)

游乐场在这里

cap*_*ian 5

没有显式泛型的替代解决方案

type NodeCallback<T> = (node: Node) => Promise<T>

const myAsyncFunction = <R,>(node: Node, cb: NodeCallback<R>) => {
  return cb(node)
}

const result = myAsyncFunction(
  document,
  (node: Node) => Promise.resolve(node.nodeType)
) // Promise<number>
Run Code Online (Sandbox Code Playgroud)

我认为我们根本不需要NodeCallbacktype 中的条件类型,因为 TS 能够推断类型

操场

在这里 您可以找到有关使用回调的更多信息