Skip to content

Commit

Permalink
Improve manual TS typings for go utils
Browse files Browse the repository at this point in the history
  • Loading branch information
Siegrift committed Aug 2, 2023
1 parent e60c7b6 commit b51a0af
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/go/go.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const createGoError = <E extends Error>(err: unknown): GoResultError<E> => {
return fail(new GoWrappedError(err));
};

export const goSync = <T, E extends Error>(fn: () => T): GoResult<T, E> => {
export const goSync = <T, E extends Error = Error>(fn: () => T): GoResult<T, E> => {
try {
return success(fn());
} catch (err) {
Expand Down Expand Up @@ -72,8 +72,8 @@ export interface GoAsyncOptions {
timeoutMs: number;
}

export const go = async <T, E extends Error>(
fn: () => T,
export const go = async <T, E extends Error = Error>(
fn: () => Promise<T>,
options?: GoAsyncOptions
): Promise<GoResult<Awaited<T>, E>> => {
try {
Expand Down
15 changes: 15 additions & 0 deletions test/go.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,21 @@ describe('basic go usage', () => {
});
expect(res).toEqual(fail(err));
});

it('allows to specify the type of the returned value', async () => {
const goResOnlyData = await go<string | number>(() => {
return Promise.resolve(123);
});
assertGoSuccess(goResOnlyData);
expectType<string | number>(goResOnlyData.data);

class CustomError extends Error {}
const goResBoth = await go<string | number, CustomError>(() => {
return Promise.resolve(123);
});
assertGoSuccess(goResBoth);
expectType<string | number>(goResBoth.data);
});
});

describe('basic timeout usage', () => {
Expand Down

0 comments on commit b51a0af

Please sign in to comment.