Repository: true-myth/true-myth (ts)

Issue:
[Task] all() does not preserve types in order
Instead of preserving the types in order as they are given it returns a union type of all `Task`s which makes it impossible without a type guard to differentiate between all items in the given Array.

```ts
const a = Task.resolve<string, Error>('');
const b = Task.resolve<number, Error>(42);
const c = Task.resolve<boolean, Error>(true);

// const d: Result<(string | number | boolean)[], Error>
const d = await all([a, b, c]);
// (parameter) e: (string | number | boolean)[] instead of [string, number, boolean]
d.map((e) => {
    // const f: string | number | boolean | undefined instead of const f: string
    const f = e[0];
});
```

---

My assumption was that it should work exactly like `Promise.all()`

```ts
const a = Promise.resolve<string>('');
const b = Promise.resolve<number>(42);
const c = Promise.resolve<boolean>(true);

// Correctly infers const d: [string, number, boolean]
const d = await Promise.all([a, b, c]);
// Correctly infers const e: string
const e = d[0];
```

Pull request:
Bug: `all` and `any` should preserve order of types
When I originally implemented these, I was rusty on the relevant type- level shenanigans that would be required to make them type check, but an unrelated bit of TypeScript work reminded me that we can use variadic generics in exactly this kind of scenario: we “just” need to constrain the relevant type aliases to use `[...TheRelevantType]` instead of using `[number]` to index them as arrays, and then also update the implementations to preserve that ordering.

The runtime implication is small:

1. Use `Array.prototype.entries` to enumerate the tasks and thereby save which `Task` is resolving or rejecting at any given point in `all` or `any` respectively.

2. Pre-allocate an array with the same length of the original array of tasks, so that it can be filled in at the appropriate location. This implies that the array will be “sparse” during the lifecycle of the function unless or until all the tasks resolve or reject for `all` and `any` respectively. This will never be visible to the caller, as the array will be returned full *or* garbage collected as unused.

In most cases, I expect the potential additional allocation overhead to be irrelevant: if anything, we may end up allocating *smaller* arrays this way

This is a bug fix that *will* produce red squiggles, but of the sort the SemVer TS spec expressly allows: they represent code users can *delete*, because they *had* to do runtime checks before to figure out what the type was for each item in the array, i.e., where they previously might have ended up with a `Resolved<Array<string | number>>`, they now might end up with `Resolved<[string, number]>`, so `task.value[0]` will be statically known to be `string` rather than `string | number`.

I started by fixing it here as targeting the v8.x branch, because it is unexpected and does not match the types for `Promise`; I will also port it forward to the `main` branch targeting the upcoming v9.0 release.

Fixes #953.

Patch:
diff --git a/src/task.ts b/src/task.ts
index 4ae8710..8aae60a 100644
--- a/src/task.ts
+++ b/src/task.ts
@@ -804,7 +804,7 @@ export function timer(ms: number): Timer {
   @internal
  */
 export type All<A extends readonly AnyTask[]> = Task<
-  Array<TaskTypesFor<A>[0][number]>,
+  [...TaskTypesFor<A>[0]],
   TaskTypesFor<A>[1][number]
 >;
 
@@ -850,21 +850,24 @@ export type All<A extends readonly AnyTask[]> = Task<
   @template A The type of the array or tuple of tasks.
 */
 export function all(tasks: []): Task<[], never>;
-export function all<A extends readonly AnyTask[]>(tasks: A): All<A>;
+// This overload uses a variadic generic `[...A]` in both parameter and return
+// position to correctly
+export function all<A extends readonly AnyTask[]>(tasks: readonly [...A]): All<[...A]>;
 export function all<A extends readonly AnyTask[]>(tasks: A): Task<unknown, unknown> {
   if (tasks.length === 0) {
     return Task.resolve([]);
   }
 
   let total = tasks.length;
-  let oks = new Array<unknown>();
+  let oks = Array.from({ length: tasks.length });
+  let resolved = 0;
   let hasRejected = false;
 
   return new Task((resolve, reject) => {
     // Because all tasks will *always* resolve, we need to manage this manually,
     // rather than using `Promise.all`, so that we produce a rejected `Task` as
     // soon as *any* `Task` rejects.
-    for (let task of tasks) {
+    for (let [idx, task] of tasks.entries()) {
       // Instead, each `Task` wires up handlers for resolution and rejection.
       task.match({
         // If it rejected, then check whether one of the other tasks has already
@@ -891,8 +894,9 @@ export function all<A extends readonly AnyTask[]>(tasks: A): Task<unknown, unkno
             return;
           }
 
-          oks.push(value);
-          if (oks.length === total) {
+          oks[idx] = value;
+          resolved += 1;
+          if (resolved === total) {
             resolve(oks);
           }
         },
@@ -993,8 +997,8 @@ export function allSettled(tasks: AnyTask[]): Task<unknown, never> {
   console.log(result.toString()); // Err(AggregateRejection: `Task.race`: 10ms,20ms,30ms)
   ```
 
-  (Note that the order in the resulting `AggregateRejection` is not guaranteed
-  to be stable!)
+  The order in the resulting `AggregateRejection` is guaranteed to be stable and
+  to match the order of the tasks passed in.
 
   @param tasks The set of tasks to check for any resolution.
   @returns A Task which is either {@linkcode Resolved} with the value of the
@@ -1006,22 +1010,24 @@ export function allSettled(tasks: AnyTask[]): Task<unknown, never> {
 */
 export function any(tasks: []): Task<never, AggregateRejection<[]>>;
 export function any<A extends readonly AnyTask[]>(
-  tasks: A
-): Task<TaskTypesFor<A>[0][number], AggregateRejection<Array<TaskTypesFor<A>[1][number]>>>;
-export function any(tasks: [] | AnyTask[]): AnyTask {
+  tasks: readonly [...A]
+): Task<TaskTypesFor<A>[0][number], AggregateRejection<[...TaskTypesFor<A>[1]]>>;
+// export function all<A extends readonly AnyTask[]>(tasks: readonly [...A]): All<[...A]>;
+export function any(tasks: readonly [] | readonly AnyTask[]): AnyTask {
   if (tasks.length === 0) {
     return Task.reject(new AggregateRejection([]));
   }
 
   let total = tasks.length;
   let hasResolved = false;
-  let rejections = new Array<unknown>();
+  let rejections = Array.from({ length: tasks.length });
+  let rejected = 0;
 
   return new Task((resolve, reject) => {
     // We cannot use `Promise.any`, because it will only return the first `Task`
     // that resolves, and the `Promise` for a `Task` *always* either resolves if
     // it settles.
-    for (let task of tasks) {
+    for (let [idx, task] of tasks.entries()) {
       // Instead, each `Task` wires up handlers for resolution and rejection.
       task.match({
         // If it resolved, then check whether one of the other tasks has already
@@ -1048,9 +1054,10 @@ export function any(tasks: [] | AnyTask[]): AnyTask {
             return;
           }
 
-          rejections.push(reason);
+          rejections[idx] = reason;
+          rejected += 1;
 
-          if (rejections.length === total) {
+          if (rejected === total) {
             reject(new AggregateRejection(rejections));
           }
         },


Test patch:
diff --git a/test/task.test.ts b/test/task.test.ts
index c9f9f45..64c688a 100644
--- a/test/task.test.ts
+++ b/test/task.test.ts
@@ -1029,15 +1029,15 @@ describe('module-scope functions', () => {
     describe('with a single task', () => {
       test('that is still pending', () => {
         let { task } = Task.withResolvers<string, number>();
-        let result = all([task] as const);
-        expectTypeOf(result).toEqualTypeOf<Task<Array<string>, number>>();
+        let result = all([task]);
+        expectTypeOf(result).toEqualTypeOf<Task<[string], number>>();
         expect(result.state).toBe(State.Pending);
       });
 
       test('that has resolved', async () => {
         let theTask = Task.resolve('hello');
         let result = all([theTask]);
-        expectTypeOf(result).toEqualTypeOf<Task<string[], never>>();
+        expectTypeOf(result).toEqualTypeOf<Task<[string], never>>();
         await result;
         expect(result.state).toBe(State.Resolved);
         if (result.isResolved) {
@@ -1050,7 +1050,7 @@ describe('module-scope functions', () => {
         let theTask = Task.reject<string, string>(theReason);
         let result = all([theTask]);
         await result;
-        expectTypeOf(result).toEqualTypeOf<Task<string[], string>>();
+        expectTypeOf(result).toEqualTypeOf<Task<[string], string>>();
         expect(result.state).toBe(State.Rejected);
         if (result.isRejected) {
           expect(result.reason).toBe(theReason);
@@ -1062,7 +1062,7 @@ describe('module-scope functions', () => {
       test('types', () => {
         let { task: task1 } = Task.withResolvers<string, number>();
         let { task: task2 } = Task.withResolvers<boolean, Error>();
-        let fromTuple = all([task1, task2] as const);
+        let fromTuple = all([task1, task2]);
         let fromArray = all([task1, task2]);
         expectTypeOf(fromTuple).toEqualTypeOf(fromArray);
       });
@@ -1070,8 +1070,8 @@ describe('module-scope functions', () => {
       test('that are all still pending', () => {
         let { task: task1 } = Task.withResolvers<string, number>();
         let { task: task2 } = Task.withResolvers<boolean, Error>();
-        let result = all([task1, task2] as const);
-        expectTypeOf(result).toEqualTypeOf<Task<Array<string | boolean>, number | Error>>();
+        let result = all([task1, task2]);
+        expectTypeOf(result).toEqualTypeOf<Task<[string, boolean], number | Error>>();
         expect(result.state).toBe(State.Pending);
       });
 
@@ -1079,8 +1079,8 @@ describe('module-scope functions', () => {
         test('while the second is pending', async () => {
           let { task: task1, resolve: resolve1 } = Task.withResolvers<string, number>();
           let { task: task2 } = Task.withResolvers<number, boolean>();
-          let result = all([task1, task2] as const);
-          expectTypeOf(result).toEqualTypeOf<Task<Array<string | number>, number | boolean>>();
+          let result = all([task1, task2]);
+          expectTypeOf(result).toEqualTypeOf<Task<[string, number], number | boolean>>();
 
           resolve1('first');
           expect(result.state).toBe(State.Pending);
@@ -1090,14 +1090,15 @@ describe('module-scope functions', () => {
           let { task: task1, resolve: resolve1 } = Task.withResolvers<number, string>();
           let { task: task2, resolve: resolve2 } = Task.withResolvers<string, boolean>();
           let result = all([task1, task2]);
-          expectTypeOf(result).toEqualTypeOf<Task<Array<number | string>, string | boolean>>();
+          expectTypeOf(result).toEqualTypeOf<Task<[number, string], string | boolean>>();
 
           resolve2('second');
           resolve1(1);
           await result;
           expect(result.state).toBe(State.Resolved);
           if (result.isResolved) {
-            expect(result.value).toEqual(['second', 1]);
+            expectTypeOf(result.value).toEqualTypeOf<[number, string]>();
+            expect(result.value).toEqual([1, 'second']);
           }
         });
 
@@ -1105,7 +1106,7 @@ describe('module-scope functions', () => {
           let { task: task1, resolve: resolve1 } = Task.withResolvers<string, number>();
           let { task: task2, reject: reject2 } = Task.withResolvers<boolean, string>();
           let result = all([task1, task2] as const);
-          expectTypeOf(result).toEqualTypeOf<Task<Array<string | boolean>, number | string>>();
+          expectTypeOf(result).toEqualTypeOf<Task<[string, boolean], number | string>>();
 
           reject2('error');
           resolve1('first');
@@ -1122,7 +1123,7 @@ describe('module-scope functions', () => {
           let { task: task1 } = Task.withResolvers<number, boolean>();
           let { task: task2, resolve: resolve2 } = Task.withResolvers<string, Error>();
           let result = all([task1, task2] as const);
-          expectTypeOf(result).toEqualTypeOf<Task<Array<number | string>, boolean | Error>>();
+          expectTypeOf(result).toEqualTypeOf<Task<[number, string], boolean | Error>>();
 
           resolve2('second');
           expect(result.state).toBe(State.Pending);
@@ -1132,7 +1133,7 @@ describe('module-scope functions', () => {
           let { task: task1, resolve: resolve1 } = Task.withResolvers<string, number>();
           let { task: task2, resolve: resolve2 } = Task.withResolvers<number, boolean>();
           let result = all([task1, task2] as const);
-          expectTypeOf(result).toEqualTypeOf<Task<Array<string | number>, number | boolean>>();
+          expectTypeOf(result).toEqualTypeOf<Task<[string, number], number | boolean>>();
 
           resolve1('first');
           resolve2(2);
@@ -1147,7 +1148,7 @@ describe('module-scope functions', () => {
           let { task: task1, reject: reject1 } = Task.withResolvers<number, string>();
           let { task: task2, resolve: resolve2 } = Task.withResolvers<string, boolean>();
           let result = all([task1, task2] as const);
-          expectTypeOf(result).toEqualTypeOf<Task<Array<number | string>, string | boolean>>();
+          expectTypeOf(result).toEqualTypeOf<Task<[number, string], string | boolean>>();
 
           reject1('error');
           resolve2('second');
@@ -1164,7 +1165,7 @@ describe('module-scope functions', () => {
       let { task: task1, reject: reject1 } = Task.withResolvers<number, string>();
       let { task: task2 } = Task.withResolvers<string, boolean>();
       let result = all([task1, task2] as const);
-      expectTypeOf(result).toEqualTypeOf<Task<Array<number | string>, string | boolean>>();
+      expectTypeOf(result).toEqualTypeOf<Task<[number, string], string | boolean>>();
 
       reject1('error');
       await result;
@@ -1430,7 +1431,7 @@ describe('module-scope functions', () => {
           let { task: task2 } = Task.withResolvers<number, boolean>();
           let result = any([task1, task2]);
           expectTypeOf(result).toEqualTypeOf<
-            Task<string | number, AggregateRejection<Array<number | boolean>>>
+            Task<string | number, AggregateRejection<[number, boolean]>>
           >();
 
           resolve1('first');
@@ -1446,7 +1447,7 @@ describe('module-scope functions', () => {
           let { task: task2, resolve: resolve2 } = Task.withResolvers<string, boolean>();
           let result = any([task1, task2]);
           expectTypeOf(result).toEqualTypeOf<
-            Task<number | string, AggregateRejection<Array<string | boolean>>>
+            Task<number | string, AggregateRejection<[string, boolean]>>
           >();
 
           resolve2('second');
@@ -1463,7 +1464,7 @@ describe('module-scope functions', () => {
           let { task: task2, reject: reject2 } = Task.withResolvers<boolean, string>();
           let result = any([task1, task2]);
           expectTypeOf(result).toEqualTypeOf<
-            Task<string | boolean, AggregateRejection<Array<number | string>>>
+            Task<string | boolean, AggregateRejection<[number, string]>>
           >();
 
           reject2('error');
@@ -1482,7 +1483,7 @@ describe('module-scope functions', () => {
           let { task: task2 } = Task.withResolvers<number, boolean>();
           let result = any([task1, task2]);
           expectTypeOf(result).toEqualTypeOf<
-            Task<string | number, AggregateRejection<Array<number | boolean>>>
+            Task<string | number, AggregateRejection<[number, boolean]>>
           >();
 
           reject1(1);
@@ -1494,7 +1495,7 @@ describe('module-scope functions', () => {
           let { task: task2, resolve: resolve2 } = Task.withResolvers<string, boolean>();
           let result = any([task1, task2]);
           expectTypeOf(result).toEqualTypeOf<
-            Task<number | string, AggregateRejection<Array<string | boolean>>>
+            Task<number | string, AggregateRejection<[string, boolean]>>
           >();
 
           resolve2('second');
@@ -1511,7 +1512,7 @@ describe('module-scope functions', () => {
           let { task: task2, reject: reject2 } = Task.withResolvers<boolean, string>();
           let result = any([task1, task2]);
           expectTypeOf(result).toEqualTypeOf<
-            Task<string | boolean, AggregateRejection<Array<number | string>>>
+            Task<string | boolean, AggregateRejection<[number, string]>>
           >();
 
           reject2('error');
@@ -1520,8 +1521,8 @@ describe('module-scope functions', () => {
           expect(result.state).toBe(State.Rejected);
           if (result.isRejected) {
             expect(result.reason).toBeInstanceOf(AggregateRejection);
-            expect(result.reason.errors[0]!).toBe('error');
-            expect(result.reason.errors[1]!).toBe(1);
+            expect(result.reason.errors[0]!).toBe(1);
+            expect(result.reason.errors[1]!).toBe('error');
           }
         });
       });
@@ -1532,7 +1533,7 @@ describe('module-scope functions', () => {
           let { task: task2, resolve: resolve2 } = Task.withResolvers<string, Error>();
           let result = any([task1, task2]);
           expectTypeOf(result).toEqualTypeOf<
-            Task<number | string, AggregateRejection<Array<boolean | Error>>>
+            Task<number | string, AggregateRejection<[boolean, Error]>>
           >();
 
           resolve2('second');
@@ -1548,7 +1549,7 @@ describe('module-scope functions', () => {
           let { task: task2, resolve: resolve2 } = Task.withResolvers<number, boolean>();
           let result = any([task1, task2]);
           expectTypeOf(result).toEqualTypeOf<
-            Task<string | number, AggregateRejection<Array<number | boolean>>>
+            Task<string | number, AggregateRejection<[number, boolean]>>
           >();
 
           resolve1('first');
@@ -1565,7 +1566,7 @@ describe('module-scope functions', () => {
           let { task: task2, resolve: resolve2 } = Task.withResolvers<string, boolean>();
           let result = any([task1, task2]);
           expectTypeOf(result).toEqualTypeOf<
-            Task<number | string, AggregateRejection<Array<string | boolean>>>
+            Task<number | string, AggregateRejection<[string, boolean]>>
           >();
 
           reject1('error');
@@ -1585,7 +1586,7 @@ describe('module-scope functions', () => {
         let { task: task2, reject: reject2 } = Task.withResolvers<string, number>();
         let result = any([task1, task2]);
         expectTypeOf(result).toEqualTypeOf<
-          Task<number | string, AggregateRejection<Array<boolean | number>>>
+          Task<number | string, AggregateRejection<[boolean, number]>>
         >();
 
         reject2(2);
@@ -1597,7 +1598,7 @@ describe('module-scope functions', () => {
         let { task: task2, reject: reject2 } = Task.withResolvers<number, boolean>();
         let result = any([task1, task2]);
         expectTypeOf(result).toEqualTypeOf<
-          Task<string | number, AggregateRejection<Array<number | boolean>>>
+          Task<string | number, AggregateRejection<[number, boolean]>>
         >();
 
         resolve1('first');
@@ -1614,7 +1615,7 @@ describe('module-scope functions', () => {
         let { task: task2, reject: reject2 } = Task.withResolvers<string, boolean>();
         let result = any([task1, task2] as const);
         expectTypeOf(result).toEqualTypeOf<
-          Task<number | string, AggregateRejection<Array<string | boolean>>>
+          Task<number | string, AggregateRejection<[string, boolean]>>
         >();
 
         reject1('error');