是可能从一个泛型类型的数组/元组中提取泛型参数作为数组/元组吗?

huangapple go评论98阅读模式
英文:

Is it possible to extract generic arguments of a type as an array/tuple from an array/tuple of generic types?

问题

I have translated the code portions you provided. Here they are:

  1. 要创建一个函数,该函数接受一组通用函数,并将它们“zip”成一个单一函数,该函数接受所有输入函数的参数并在一次调用中返回所有函数的输出。我唯一能够使其类型安全的方法是使用`infer`来推断每个通用函数的各个组件:
  2. type Fn<T = any, TReturn = any> = (arg: T) => TReturn;
  3. type FnArg<T extends Fn> = T extends Fn<infer TArg> ? TArg : unknown;
  4. type FnArgTuple<T extends Fn[]> = { [key in keyof T]: FnArg<T[key]> };
  5. type FnReturn<T extends Fn> = T extends Fn<any, infer TReturn> ? TReturn : unknown;
  6. type FnReturnTuple<T extends Fn[]> = { [key in keyof T]: FnReturn<T[key]> };
  7. const fnZip = <T extends ((arg: any) => any)[]>(
  8. fns: [...T],
  9. ): Fn<FnArgTuple<T>, FnReturnTuple<T>> => (
  10. args,
  11. ) => fns.map((fn, idx) => fn(args[idx])) as FnReturnTuple<T>;

然而,我想知道是否有更优雅和/或符合惯用法的方法来从给定的函数数组中提取函数的参数和返回类型作为元组。这里是一个(不工作的)示例,说明我的意思:

  1. type Fn<T = any, TReturn = any> = (arg: T) => TReturn;
  2. const fnZip = <T extends any[], TReturn extends any[]>(
  3. fns: { [key: number]: Fn<T[key], TReturn[key]> },
  4. ): Fn<T, TReturn> => (args) => fns.map((fn, idx) => fn(args[idx])) as TReturn;

编辑:我实际上想表达的是以下内容:

  1. [Type<A1, B1>, Type<A2, B2>, ...etc] => Type<[A1, A2, ..etc], [B1, B2, ...etc]>

编辑:@jcalz提出的解决方案本来是完美的,如果TS可以正确推断第二个通用类型,但出于不明原因它不起作用:

  1. type Fn<T = any, TReturn = any> = (arg: T) => TReturn;
  2. const fnZip = <T extends any[], TReturn extends { [key in keyof T]: any }>(
  3. fns: [...{ [key in keyof T]: Fn<T[key], TReturn[key]> }],
  4. ): Fn<T, TReturn> => (args) => fns.map((fn, idx) => fn(args[idx])) as TReturn;
  5. const zipped = fnZip([
  6. (x: string) => x.length,
  7. (y: number) => y.toFixed(),
  8. ]);

希望这对你有所帮助。如果需要更多信息,请告诉我。

英文:

I want to create a function that takes an array of generic functions and "zips" them into a single function that takes all of the input functions' arguments and returns all of the outputs of those functions in a single call. The only way I was able to make it type-safe is with infer'ing each generic functions' individual component:

  1. type Fn&lt;T = any, TReturn = any&gt; = (arg: T) =&gt; TReturn;
  2. type FnArg&lt;T extends Fn&gt; = T extends Fn&lt;infer TArg&gt; ? TArg : unknown;
  3. type FnArgTuple&lt;T extends Fn[]&gt; = { [key in keyof T]: FnArg&lt;T[key]&gt; };
  4. type FnReturn&lt;T extends Fn&gt; = T extends Fn&lt;any, infer TReturn&gt; ? TReturn : unknown;
  5. type FnReturnTuple&lt;T extends Fn[]&gt; = { [key in keyof T]: FnReturn&lt;T[key]&gt; };
  6. const fnZip = &lt;T extends ((arg: any) =&gt; any)[]&gt;(
  7. fns: [...T],
  8. ): Fn&lt;FnArgTuple&lt;T&gt;, FnReturnTuple&lt;T&gt;&gt; =&gt; (
  9. args,
  10. ) =&gt; fns.map((fn, idx) =&gt; fn(args[idx])) as FnReturnTuple&lt;T&gt;;

However, I was wondering whether there was more elegant and/or idiomatic way to extract functions' arguments and return types as tuples from a given array of functions. Here's a (non-working) illustration of what I mean:

  1. type Fn&lt;T = any, TReturn = any&gt; = (arg: T) =&gt; TReturn;
  2. const fnZip = &lt;T extends any[], TReturn extends any[]&gt;(
  3. fns: { [key: number]: Fn&lt;T[key], TReturn[key]&gt; },
  4. ): Fn&lt;T, TReturn&gt; =&gt; (args) =&gt; fns.map((fn, idx) =&gt; fn(args[idx])) as TReturn;

EDIT: What I effectively want to express is the following:

  1. [Type&lt;A1, B1&gt;, Type&lt;A2, B2&gt;, ...etc] =&gt; Type&lt;[A1, A2, ..etc], [B1, B2, ...etc]&gt;

EDIT: @jcalz proposed a solution that would've worked perfectly if TS could infer the second generic type correctly, but it doesn't for unknown reason:

  1. type Fn&lt;T = any, TReturn = any&gt; = (arg: T) =&gt; TReturn;
  2. const fnZip = &lt;T extends any[], TReturn extends { [key in keyof T]: any }&gt;(
  3. fns: [...{ [key in keyof T]: Fn&lt;T[key], TReturn[key]&gt; }],
  4. ): Fn&lt;T, TReturn&gt; =&gt; (args) =&gt; fns.map((fn, idx) =&gt; fn(args[idx])) as TReturn;
  5. const zipped = fnZip([
  6. // ^? const zipped: Fn&lt;[string, number], [any, any]&gt;
  7. (x: string) =&gt; x.length,
  8. (y: number) =&gt; y.toFixed(),
  9. ]);

答案1

得分: 1

以下是您要翻译的内容:

"The "elegant" answer to your question is to use two generic type parameters, corresponding to the tuple A of function argument types and the tuple R of their corresponding return types, and then the input fns would be a mapped type over one of these (say, A):

  1. const fnZip = <A extends any[], R extends { [I in keyof A]: any }>(
  2. fns: [...{ [I in keyof A]: Fn<A[I], R[I]> }],
  3. ): Fn<A, R> => (args) => fns.map((fn, idx) => fn(args[idx])) as R;

(Well, it's actually a mapped type wrapped in a variadic tuple type to prompt the compiler to infer a tuple type for A instead of some unordered array type of arbitrary length.)

That version "works", in the sense that if you manually specify the A and R type arguments, you'll get the expected output:

  1. const zipped = fnZip<[string, number], [number, string]>(
  2. [x => x.length, y => y.toFixed(2)]
  3. );
  4. // const zipped: Fn<[string, number], [number, string]> 👍

But if you'd like the type arguments to be inferred, you're going to have a bad time:

  1. const zipped = fnZip([(x: string) => x.length, (y: number) => y.toFixed(2)]);
  2. // const zipped: Fn<[string, number], [any, any]> 👎

Here A is inferred correctly but R is not. That's because inference from mapped types only infers the type whose properties you're mapping over. Since fns's type maps over the keys of A, only A can get properly inferred. R ends up falling back to the constraint.

You can switch to R instead of A but that just moves the problem:

  1. const fnZip = <A extends { [I in keyof R]: any }, R extends any[]>(
  2. fns: [...{ [I in keyof R]: Fn<A[I], R[I]> }],
  3. ): Fn<A, R> => (args) => fns.map((fn, idx) => fn(args[idx])) as R;
  4. const zipped = fnZip([(x: string) => x.length, (y: number) => y.toFixed(2)]);
  5. // const zipped: Fn<[any, any], [number, string]> 👎

You could try to make it a mapped type over both A and R at once somehow, but everything I tried either didn't help or caused at least one compiler error somewhere, and the quotation marks around the word "elegant" were becoming more and more sarcastic as I tried different and weirder things. Here's the closest I could get:

  1. const fnZip = <A extends { [I in keyof R]: any } & any[], R extends { [I in keyof A]: any }>(
  2. fns: [...{ [I in keyof (A & R)]: Fn<A[I], R[I]> }], // error!
  3. // -> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. // A rest element type must be an array type.(2574)
  5. ): Fn<A, R> => (args) => fns.map((fn, idx) => fn(args[idx])) as R;
  6. const zipped = fnZip([(x: string) => x.length, (y: number) => y.toFixed(2)]);
  7. // const zipped: Fn<[string, number], [number, string]> 👍

Here the inference works, hooray! But the call signature causes a compiler error I can't resolve without breaking the inference.

For now, this doesn't quite look possible. Even if I found a way that worked I'd be worried that it'd be too fragile to rely on. This is at or beyond the edge of TypeScript's abilities right now.

Instead I think it's much more straightforward to make the inference work out by doing the simple thing of having fns's type be the type parameter F or [...F], and then spend a little effort unrolling that into A and R. Like you've done, or like this:

  1. const fnZip = <F extends ((arg: any) => any)[]>(
  2. fns: [...F]
  3. ): (args: { [I in keyof F]: Parameters<F[I]>[0] }) =>
  4. fns.map((fn, idx) => fn(args[idx])) as
  5. { [I in keyof F]: ReturnType<F[I]> };

And it's a judgment call but I wouldn't say it's that inelegant. And it has the benefit of actually working:

  1. const zipped = fnZip([(x: string) => x.length, (y: number) => y.toFixed(2)]);
  2. // const z: (args: [string, number]) => [number, string] 😊

[Playground link to code](https://www.typescriptlang.org/play?noErrorTruncation=true&ts=5.0.4#code/HYQwtgpgzgDiDGEAEApeIA2AvJBvAUEkgC4CeMyAYsADwCCANEgEoB8SAvEgBQgBOAcwBcSOgEpO7ZgG58hJKEiwEyAKIYIAkMGIBJKAAsAQgFc9wAGYQ+EYIkogAlhih45RIvAD2wKMSQWwABajjCcSPRIEAAexLYAJq7apADaALpMzFGxCa64SCm6SI7ASADWEKReFqJpIslIAL6s3PIeAb4iKQB0vfmFxaUVVTV0dUjU9IUZLNPsjRltSGIik4ws7BzsvIJQElsdUN1gIDDc3IFMjvHR++yBOwJQKdfRaWISIK4y7h7evv4sKEKPEABJgMDhQIhGA0FJ+PglARMYAmMAAI2sMxSqIx1iYCKRaRaSyIKWikiQ0W6GmAAmIBiYpEppG6xC8lEc0Qg8W4ACYxGklmJZO0APRipD-PxI

英文:

The "elegant" answer to your question is to use two generic type parameters, corresponding to the tuple A of function argument types and the tuple R of their corresponding return types, and then the input fns would be a mapped type over one of these (say, A):

  1. const fnZip = &lt;A extends any[], R extends { [I in keyof A]: any }&gt;(
  2. fns: [...{ [I in keyof A]: Fn&lt;A[I], R[I]&gt; }],
  3. ): Fn&lt;A, R&gt; =&gt; (args) =&gt; fns.map((fn, idx) =&gt; fn(args[idx])) as R;

(Well, it's actually a mapped type wrapped in a variadic tuple type to prompt the compiler to infer a tuple type for A instead of some unordered array type of arbitrary length.)

That version "works", in the sense that if you manually specify the A and R type arguments, you'll get the expected output:

  1. const zipped = fnZip&lt;[string, number], [number, string]&gt;(
  2. [x =&gt; x.length, y =&gt; y.toFixed(2)]
  3. );
  4. // const zipped: Fn&lt;[string, number], [number, string]&gt; &#128077;

But if you'd like the type arguments to be inferred, you're going to have a bad time:

  1. const zipped = fnZip([(x: string) =&gt; x.length, (y: number) =&gt; y.toFixed(2)]);
  2. // const zipped: Fn&lt;[string, number], [any, any]&gt; &#128078;

Here A is inferred correctly but R is not. That's because inference from mapped types only infers the type whose properties you're mapping over. Since fns's type maps over the keys of A, only A can get properly inferred. R ends up falling back to the constraint.

You can switch to R instead of A but that just moves the problem:

  1. const fnZip = &lt;A extends { [I in keyof R]: any }, R extends any[]&gt;(
  2. fns: [...{ [I in keyof R]: Fn&lt;A[I], R[I]&gt; }],
  3. ): Fn&lt;A, R&gt; =&gt; (args) =&gt; fns.map((fn, idx) =&gt; fn(args[idx])) as R;
  4. const zipped = fnZip2([(x: string) =&gt; x.length, (y: number) =&gt; y.toFixed(2)]);
  5. // const zipped: Fn&lt;[any, any], [number, string]&gt; &#128078;

You could try to make it a mapped type over both A and R at once somehow, but everything I tried either didn't help or caused at least one compiler error somewhere, and the quotation marks around the word "elegant" were becoming more and more sarcastic as I tried different and weirder things. Here's the closest I could get:

  1. const fnZip = &lt;A extends { [I in keyof R]: any } &amp; any[], R extends { [I in keyof A]: any }&gt;(
  2. fns: [...{ [I in keyof (A &amp; R)]: Fn&lt;A[I], R[I]&gt; }], // error!
  3. // -&gt; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. // A rest element type must be an array type.(2574)
  5. ): Fn&lt;A, R&gt; =&gt; (args) =&gt; fns.map((fn, idx) =&gt; fn(args[idx])) as R;
  6. const zipped = fnZip([(x: string) =&gt; x.length, (y: number) =&gt; y.toFixed(2)]);
  7. // const zipped: Fn&lt;[string, number], [number, string]&gt; &#128077;

Here the inference works, hooray! But the call signature causes a compiler error I can't resolve without breaking the inference.

For now, this doesn't quite look possible. Even if I found a way that worked I'd be worried that it'd be too fragile to rely on. This is at or beyond the edge of TypeScript's abilities right now.


Instead I think it's much more straightforward to make the inference work out by doing the simple thing of having fns's type be the type parameter F or [...F], and then spend a little effort unrolling that into A and R. Like you've done, or like this:

  1. const fnZip = &lt;F extends ((arg: any) =&gt; any)[]&gt;(
  2. fns: [...F]
  3. ) =&gt; (args: { [I in keyof F]: Parameters&lt;F[I]&gt;[0] }) =&gt;
  4. fns.map((fn, idx) =&gt; fn(args[idx])) as
  5. { [I in keyof F]: ReturnType&lt;F[I]&gt; };

And it's a judgment call but I wouldn't say it's that inelegant. And it has the benefit of actually working:

  1. const zipped = fnZip([(x: string) =&gt; x.length, (y: number) =&gt; y.toFixed(2)]);
  2. // const z: (args: [string, number]) =&gt; [number, string] &#128578;

Playground link to code

答案2

得分: 0

I think it's safe to say the answer is no.

And I say that because Ben Lesh, and the brilliant people he works with to create and improve RXJS don't have a great answer either despite RXJS being wildly popular, open source code.

So if there was an elegant solution, they'd adopt it.

Instead, (as of 7-MAY-2023), their solution is a brute-force method of overloading, 0 through 9 arguments, and then for the 10th argument onward the code is "now we're getting silly so just make sure they're single-parameter functions and call that good enough!"

  1. import { identity } from './identity';
  2. import { UnaryFunction } from '../types';
  3. export function pipe(): typeof identity;
  4. export function pipe<T, A>(fn1: UnaryFunction<T, A>): UnaryFunction<T, A>;
  5. export function pipe<T, A, B>(fn2: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>): UnaryFunction<T, B>;
  6. export function pipe<T, A, B, C>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>): UnaryFunction<T, C>;
  7. export function pipe<T, A, B, C, D>(
  8. fn1: UnaryFunction<T, A>,
  9. fn2: UnaryFunction<A, B>,
  10. fn3: UnaryFunction<B, C>,
  11. fn4: UnaryFunction<C, D>
  12. ): UnaryFunction<T, D>;
  13. // ... (more overloaded functions) ...
  14. /**
  15. * pipe() can be called on one or more functions, each of which can take one argument ("UnaryFunction")
  16. * and uses it to return a value.
  17. * It returns a function that takes one argument, passes it to the first UnaryFunction, and then
  18. * passes the result to the next one, passes that result to the next one, and so on.
  19. */
  20. export function pipe(...fns: Array<UnaryFunction<any, any>>): UnaryFunction<any, any> {
  21. return pipeFromArray(fns);
  22. }
  23. /** @internal */
  24. export function pipeFromArray<T, R>(fns: Array<UnaryFunction<T, R>>): UnaryFunction<T, R> {
  25. if (fns.length === 0) {
  26. return identity as UnaryFunction<any, any>;
  27. }
  28. if (fns.length === 1) {
  29. return fns[0];
  30. }
  31. return function piped(input: T): R {
  32. return fns.reduce((prev: any, fn: UnaryFunction<T, R>) => fn(prev), input as any);
  33. };
  34. }

My advice to you is to use RXJS's solution instead of writing your own. If their code was insufficient then they'd have changed it. Also, if you're already using RXJS as a dependency, or don't mind including it, then you'll get any improvements automatically.

英文:

I think it's safe to say the answer is no.

And I say that because Ben Lesh, and the brilliant people he works with to create and improve RXJS don't have a great answer either despite RXJS being wildly popular, open source code.

So if there was an elegant solution, they'd adopt it.

Instead, (as of 7-MAY-2023), their solution is a brute-force method of overloading, 0 through 9 arguments, and then for the 10th argument onward the code is "now we're getting silly so just make sure they're single-parameter functions and call that good enough!"

  1. import { identity } from &#39;./identity&#39;;
  2. import { UnaryFunction } from &#39;../types&#39;;
  3. export function pipe(): typeof identity;
  4. export function pipe&lt;T, A&gt;(fn1: UnaryFunction&lt;T, A&gt;): UnaryFunction&lt;T, A&gt;;
  5. export function pipe&lt;T, A, B&gt;(fn1: UnaryFunction&lt;T, A&gt;, fn2: UnaryFunction&lt;A, B&gt;): UnaryFunction&lt;T, B&gt;;
  6. export function pipe&lt;T, A, B, C&gt;(fn1: UnaryFunction&lt;T, A&gt;, fn2: UnaryFunction&lt;A, B&gt;, fn3: UnaryFunction&lt;B, C&gt;): UnaryFunction&lt;T, C&gt;;
  7. export function pipe&lt;T, A, B, C, D&gt;(
  8. fn1: UnaryFunction&lt;T, A&gt;,
  9. fn2: UnaryFunction&lt;A, B&gt;,
  10. fn3: UnaryFunction&lt;B, C&gt;,
  11. fn4: UnaryFunction&lt;C, D&gt;
  12. ): UnaryFunction&lt;T, D&gt;;
  13. export function pipe&lt;T, A, B, C, D, E&gt;(
  14. fn1: UnaryFunction&lt;T, A&gt;,
  15. fn2: UnaryFunction&lt;A, B&gt;,
  16. fn3: UnaryFunction&lt;B, C&gt;,
  17. fn4: UnaryFunction&lt;C, D&gt;,
  18. fn5: UnaryFunction&lt;D, E&gt;
  19. ): UnaryFunction&lt;T, E&gt;;
  20. export function pipe&lt;T, A, B, C, D, E, F&gt;(
  21. fn1: UnaryFunction&lt;T, A&gt;,
  22. fn2: UnaryFunction&lt;A, B&gt;,
  23. fn3: UnaryFunction&lt;B, C&gt;,
  24. fn4: UnaryFunction&lt;C, D&gt;,
  25. fn5: UnaryFunction&lt;D, E&gt;,
  26. fn6: UnaryFunction&lt;E, F&gt;
  27. ): UnaryFunction&lt;T, F&gt;;
  28. export function pipe&lt;T, A, B, C, D, E, F, G&gt;(
  29. fn1: UnaryFunction&lt;T, A&gt;,
  30. fn2: UnaryFunction&lt;A, B&gt;,
  31. fn3: UnaryFunction&lt;B, C&gt;,
  32. fn4: UnaryFunction&lt;C, D&gt;,
  33. fn5: UnaryFunction&lt;D, E&gt;,
  34. fn6: UnaryFunction&lt;E, F&gt;,
  35. fn7: UnaryFunction&lt;F, G&gt;
  36. ): UnaryFunction&lt;T, G&gt;;
  37. export function pipe&lt;T, A, B, C, D, E, F, G, H&gt;(
  38. fn1: UnaryFunction&lt;T, A&gt;,
  39. fn2: UnaryFunction&lt;A, B&gt;,
  40. fn3: UnaryFunction&lt;B, C&gt;,
  41. fn4: UnaryFunction&lt;C, D&gt;,
  42. fn5: UnaryFunction&lt;D, E&gt;,
  43. fn6: UnaryFunction&lt;E, F&gt;,
  44. fn7: UnaryFunction&lt;F, G&gt;,
  45. fn8: UnaryFunction&lt;G, H&gt;
  46. ): UnaryFunction&lt;T, H&gt;;
  47. export function pipe&lt;T, A, B, C, D, E, F, G, H, I&gt;(
  48. fn1: UnaryFunction&lt;T, A&gt;,
  49. fn2: UnaryFunction&lt;A, B&gt;,
  50. fn3: UnaryFunction&lt;B, C&gt;,
  51. fn4: UnaryFunction&lt;C, D&gt;,
  52. fn5: UnaryFunction&lt;D, E&gt;,
  53. fn6: UnaryFunction&lt;E, F&gt;,
  54. fn7: UnaryFunction&lt;F, G&gt;,
  55. fn8: UnaryFunction&lt;G, H&gt;,
  56. fn9: UnaryFunction&lt;H, I&gt;
  57. ): UnaryFunction&lt;T, I&gt;;
  58. export function pipe&lt;T, A, B, C, D, E, F, G, H, I&gt;(
  59. fn1: UnaryFunction&lt;T, A&gt;,
  60. fn2: UnaryFunction&lt;A, B&gt;,
  61. fn3: UnaryFunction&lt;B, C&gt;,
  62. fn4: UnaryFunction&lt;C, D&gt;,
  63. fn5: UnaryFunction&lt;D, E&gt;,
  64. fn6: UnaryFunction&lt;E, F&gt;,
  65. fn7: UnaryFunction&lt;F, G&gt;,
  66. fn8: UnaryFunction&lt;G, H&gt;,
  67. fn9: UnaryFunction&lt;H, I&gt;,
  68. ...fns: UnaryFunction&lt;any, any&gt;[]
  69. ): UnaryFunction&lt;T, unknown&gt;;
  70. /**
  71. * pipe() can be called on one or more functions, each of which can take one argument (&quot;UnaryFunction&quot;)
  72. * and uses it to return a value.
  73. * It returns a function that takes one argument, passes it to the first UnaryFunction, and then
  74. * passes the result to the next one, passes that result to the next one, and so on.
  75. */
  76. export function pipe(...fns: Array&lt;UnaryFunction&lt;any, any&gt;&gt;): UnaryFunction&lt;any, any&gt; {
  77. return pipeFromArray(fns);
  78. }
  79. /** @internal */
  80. export function pipeFromArray&lt;T, R&gt;(fns: Array&lt;UnaryFunction&lt;T, R&gt;&gt;): UnaryFunction&lt;T, R&gt; {
  81. if (fns.length === 0) {
  82. return identity as UnaryFunction&lt;any, any&gt;;
  83. }
  84. if (fns.length === 1) {
  85. return fns[0];
  86. }
  87. return function piped(input: T): R {
  88. return fns.reduce((prev: any, fn: UnaryFunction&lt;T, R&gt;) =&gt; fn(prev), input as any);
  89. };
  90. }

My advice to you is to use RXJS's solution instead of writing your own. If their code was insufficient then they'd have changed it. Also, if you're already using RXJS as a dependency, or don't mind including it, then you'll get any improvements automatically.

huangapple
  • 本文由 发表于 2023年5月7日 06:02:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191363.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定