Skip to content

Commit

Permalink
Fix asyncFn type
Browse files Browse the repository at this point in the history
  • Loading branch information
bkiac committed Nov 16, 2023
1 parent 34ba0db commit c70db1a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 22 deletions.
31 changes: 10 additions & 21 deletions src/fn.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,21 @@
import type {Result} from "./result"
import {PromiseResult} from "./promise_result"
import type {Err, InferErr, InferOk, Ok} from "./internal"
import type {InferErr, InferOk} from "./internal"

export function fn<A extends any[], R extends Result<any, any>>(
f: (...args: A) => R,
): (...args: A) => Result<InferOk<R>, InferErr<R>> {
return f
}

export function asyncFn<A extends any[], T>(
f: (...args: A) => Promise<Ok<T>>,
): (...args: A) => PromiseResult<T, never>
export function asyncFn<A extends any[], E>(
f: (...args: A) => Promise<Err<E>>,
): (...args: A) => PromiseResult<never, E>
export function asyncFn<A extends any[], T, E>(
f: (...args: A) => Promise<Ok<T> | Err<E>>,
): (...args: A) => PromiseResult<T, E>
export function asyncFn<A extends any[], T, E>(
f: (...args: A) => Promise<Result<T, E>>,
): (...args: A) => PromiseResult<T, E>
export function asyncFn<A extends any[], T, E>(
f: (...args: A) => PromiseResult<T, E>,
): (...args: A) => PromiseResult<T, E>
export function asyncFn<A extends any[], T, E>(
f: (...args: A) => Promise<Ok<T> | Err<E> | Result<T, E>> | PromiseResult<T, E>,
): (...args: A) => PromiseResult<T, E> {
return function (...args: A) {
return new PromiseResult<T, E>(f(...args))
export function asyncFn<A extends any[], R extends PromiseResult<any, any>>(
f: (...args: A) => R,
): (...args: A) => PromiseResult<InferOk<Awaited<R>>, InferErr<Awaited<R>>>
export function asyncFn<A extends any[], R extends Promise<Result<any, any>>>(
f: (...args: A) => R,
): (...args: A) => PromiseResult<InferOk<Awaited<R>>, InferErr<Awaited<R>>>
export function asyncFn(f: any): any {
return function (...args: any[]) {
return new PromiseResult(f(...args))
}
}
10 changes: 9 additions & 1 deletion test/fn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,19 @@ describe.concurrent("asyncFn", () => {
if (Math.random() > 0.5) {
return Ok(1)
}
if (Math.random() > 0.5) {
return Ok("foo")
}
if (Math.random() > 0.5) {
return Err(1)
}
return Err("error")
}
const wrapped = asyncFn(f)
expectTypeOf(wrapped).parameter(0).toBeNumber()
expectTypeOf(wrapped).returns.toEqualTypeOf<PromiseResult<number, string>>()
expectTypeOf(wrapped).returns.toEqualTypeOf<
PromiseResult<number | string, number | string>
>()
})

it("returns correct type with function returning Promise<Ok>", () => {
Expand Down

0 comments on commit c70db1a

Please sign in to comment.