我已经编写了一个类型脚本函数,该函数在给定关系类型、方向和名义nodeID的情况下,返回该关系另一端的 node 列表.例如
("A_TO_B", "from", "nodeAId") -> NodeB[]
是否有可能在不传递显式类型参数的情况下键入此函数,从而使TypeScrip正确地缩小/推断返回类型?
奇怪的是,在我当前的实现中,如果调用方显式传递前两个泛型类型参数,则推理确实有效:
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"
// this does not infer the return type correctly... :(
const res = getNeighborsByRelationship('APPLE_TO_CLOCK_AND_DOGGIE', 'from', id)
// however, this does:
// const res = getNeighborsByRelationship<'APPLE_TO_CLOCK_AND_DOGGIE', 'from'>('APPLE_TO_CLOCK_AND_DOGGIE', 'from', id)
return res?.nodes[0].label
}
但是,如果不显式传递泛型类型,我就无法使推理工作.
我当前的工作是可复制的,并且包括示例 node 和关系类型,它包含在playground 链接中.提供Node和Relationship类型的 struct 只是为了方便,因为在我工作的代码库中不容易更改它们.