gpt4 book ai didi

typescript - 如何让 TS 在通用构建器函数中推断回调?

转载 作者:行者123 更新时间:2023-12-04 11:16:50 27 4
gpt4 key购买 nike

考虑以下用例演示 ( playground ):

// A builder that can self-reference its keys using a ref function
declare function makeObj<K extends string>(
builder: (ref: (k: K) => number) => Record<K, number>
): Record<K, number>;

// Not using `ref` for now. All good, K is inferred as <"x" | "y">.
const obj1 = makeObj(() => ({ x: 1, y: 2 }));

// Oops, now that we try to use `ref`, K is inferred as <string>.
const obj2 = makeObj(ref => ({ x: 1, y: ref("invalid key, only x or y") }));

// This works, but we'd want K to be automatically inferred.
const obj3 = makeObj<"x" | "y">(ref => ({ x: 1, y: ref("x") }));
那么,我应该怎么写 makeObj所以 K是自动推断的?

最佳答案

尝试声明 Record<K, number>作为第二个泛型类型。
playground

declare function makeObj<K extends string, T extends Record<K, number> = Record<K, number>>(
builder: (ref: (k: K) => number) => T
): T

const obj1 = makeObj(() => ({ x: 1, y: 2 }));
const obj2 = makeObj(ref => ({ x: 1, y: ref("invalid key, only x or y") }));
const obj3 = makeObj(ref => ({ x: 1, y: ref("x") }));
局限性
好吧,正如@kaya3 在下面评论的那样。
这个解析只能推断返回类型。
除非明确设置泛型类型,否则它仍然无法找到无效键。
// error will shown when given explicit generic type
const obj2 = makeObj<'x' | 'y'>(ref => ({x: 1, y: ref("invalid key, only x or y")}));

关于typescript - 如何让 TS 在通用构建器函数中推断回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68625995/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com