You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何TypeScript需显式传泛型才推断函数返回类型?能否优化?

如何让TypeScript函数自动推断返回类型,无需显式传入泛型参数?

我编写了一个TypeScript函数,它接收关系类型、方向和标称nodeId,返回该关系另一端的节点列表。例如:

("A_TO_B", "from", "nodeAId") -> NodeB[]

能否为该函数添加类型定义,使TypeScript无需传入显式泛型参数,即可正确收窄/推断返回类型?

奇怪的是,在我当前的实现中,如果调用者显式传入前两个泛型参数,推断是有效的:

export function getNeighborsByRelationship<
  T extends ExtractRelationshipsByNodeId<D>["type"],
  D extends Extract<keyof Relationship, "from" | "to"> = Extract<
    keyof Relationship,
    "from" | "to"
  >,
  R extends ExtractRelationshipByType<T> = ExtractRelationshipByType<T>,
  N extends Node = ExtractNodeById<
    R[Exclude<Extract<keyof R, "from" | "to">, D>]
  >
>(
  type: R["type"],
  dir: D,
  id: R[D]
): {
  nodes: N[];
  relationships: R[];
}

function test () {
  const id: AppleId = "A"
    
  // 此处无法正确推断返回类型... :(
  const res = getNeighborsByRelationship('APPLE_TO_CLOCK_AND_DOGGIE', 'from', id)

  // 但这样可以:
  // const res = getNeighborsByRelationship<'APPLE_TO_CLOCK_AND_DOGGIE', 'from'>('APPLE_TO_CLOCK_AND_DOGGIE', 'from', id)

  return res?.nodes[0].label
}

但我无法实现无需显式传入泛型参数的类型推断。

我已准备好包含示例Node和Relationship类型的完整可复现代码,Node和Relationship类型的结构仅作参考,因为在我当前的代码库中难以修改它们。

内容的提问来源于stack exchange,提问作者Dylan Taylor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 16:20:21