我需要帮助,将纸上写的一些具有挑战性的TS启发式伪代码转换为具体的TS。
type F<T, [x, ...r] extends ReadonlyArray<ReadonlyArray<keyof T>> =
Pick<T, ItemOf<X>> | F<T, R>;
// other approach explored
type F<T, U> =
U extends readonly [infer X, ...infer R] ?
X extends ReadonlyArray<keyof T> ?
Pick<T, ItemOf<X>> | F<T, R> : never : never;
[为了完整起见,这是一个ItemOf
定义,可以完成预期的工作,它是文字数组中的文字字符串("a" | "b" | ...
)的“副产品类型”,可以提供给Pick
:
type ItemOf<T> =
T extends ReadonlyArray<infer Item> ?
Item : never;
type Result = ItemOf<["a", "b"]> // successfully resolves to "a" | "b"
是否有可能像我尝试的那样解开类型?我知道这可能是受ML启发的,但我对它可能需要的功能感兴趣,才能使这种类型函子定义在TS上运行典型用法是:
type Struct = {x: string, y: string, z: string};
const Fields = [["x", "y"], ["z"]] as const;
type Result = F<Struct, typeof Fields> // should resolve to {x: string, y: string} | {z: string};
这对您有用吗?
type F<T, F extends readonly (readonly (keyof T)[])[]> =
{ [K in keyof F]: Pick<T, Extract<F[K], readonly (keyof T)[]>[number]> }[number]
type Result = F<Struct, typeof Fields>
// type Result = Pick<Struct, "x" | "y"> | Pick<Struct, "z">
我正在映射键数组并处理结果。请注意,您可以通过查找数组A
的属性(number
)获得数组A[number]
的元素。如果这对您有效,则可以扩展答案进行解释。如果不是,请尝试清楚地说明您的操作(我在阅读文字时遇到麻烦,对不起😳),并可能有多个示例。
希望有所帮助;祝你好运!