Skip to content

Commit

Permalink
Improve waitFor() types (#459)
Browse files Browse the repository at this point in the history
Use type arguments & inference to ensure that `waitFor()` in function form returns the same type that it was passed. This prevents it from getting in the way of passing functions as as typed arguments. For example, `ember-concurrency`'s `task()` function expects an async arrow function as its argument, so `task(async () => null)` works, but without this change, `task(waitFor(() => null))` does not because `waitFor(() => null)` is just `Function`.
  • Loading branch information
bendemboski committed Sep 8, 2023
1 parent 364d3f1 commit 790a4f6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
11 changes: 7 additions & 4 deletions addon/@ember/test-waiters/wait-for.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,14 @@ type DecoratorArguments = [object, string, PropertyDescriptor, string?];
* }
*
*/
export default function waitFor(fn: AsyncFunction<any[], any>, label?: string): Function;
export default function waitFor(
fn: CoroutineFunction<any[], any>,
export default function waitFor<A extends Array<any>, PromiseReturn>(
fn: AsyncFunction<A, PromiseReturn>,
label?: string
): AsyncFunction<A, PromiseReturn>;
export default function waitFor<A extends Array<any>, T>(
fn: CoroutineFunction<A, T>,
label?: string
): CoroutineFunction<any[], any>;
): CoroutineFunction<A, T>;
export default function waitFor(
target: object,
_key: string,
Expand Down
27 changes: 27 additions & 0 deletions tests/unit/wait-for-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,5 +445,32 @@ if (DEBUG) {
assert.deepEqual(getPendingWaiterState().pending, 0);
});
});

test('types', async function (assert) {
assert.expect(0);

async function asyncFn(a: string, b: string) {
return `${a}${b}`;
}
function* genFn(a: string, b: string) {
yield `${a}${b}`;
return `${a}${b}`;
}

function asyncNoop(fn: typeof asyncFn) {
return fn;
}
function genNoop(fn: typeof genFn) {
return fn;
}

asyncNoop(waitFor(asyncFn));
genNoop(waitFor(genFn));

// @ts-expect-error wrong argument types
waitFor(asyncFn)(1, 2);
// @ts-expect-error wrong argument types
waitFor(genFn)(1, 2);
});
});
}

0 comments on commit 790a4f6

Please sign in to comment.