Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .changeset/shy-trees-lose.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
"@maxmorozoff/try-catch-tuple": patch
---

docs:

- Add JSDoc for TryCatch types

chore:

- Export missing types
- Update default error type
- Update Branded type
- Update DataErrorTuple type (e.g., `rest` is now `never[]`)
- Restrict array methods on DataErrorTuple
- Make `fn` parameter required

refactor:

- Extract DataErrorTuple to type alias
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ type Result<T, E = Error> = ([data: T, error: null] | [data: null, error: E]) &
### Edge Cases

```ts
tryCatch(); // Returns [undefined, null]
tryCatch(undefined); // Returns [undefined, null]
tryCatch(null); // Returns [null, null]
tryCatch(() => {
throw new Error("Unexpected Error");
Expand Down
2 changes: 1 addition & 1 deletion packages/try-catch-tuple/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ type Result<T, E = Error> = [data: T, error: null] | [data: null, error: E];
## Edge Cases

```ts
tryCatch(); // Returns [undefined, null]
tryCatch(undefined); // Returns [undefined, null]
tryCatch(null); // Returns [null, null]
tryCatch(() => {
throw new Error("Unexpected Error");
Expand Down
92 changes: 77 additions & 15 deletions packages/try-catch-tuple/src/tryCatch.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,104 @@
type Branded<T> = T & { __tryCatchTupleResult: any };
type Success<T> = Branded<[data: T, error: null]>;
type Failure<E> = Branded<[data: null, error: E | Error]>;
type Result<T, E> = Success<T> | Failure<E>;
type Branded<T> = T & { __tryCatchTupleResult: never };
type DisableArrayMethods<T> = T & {
[K in Exclude<keyof Array<any>, "length" | symbol>]: never;
};

type DataErrorTuple<T, E> = Branded<
DisableArrayMethods<[data: T, error: E] & never[]>
>;

/**
* Represents a successful result where `data` is present and `error` is `null`.
*/
export type Success<T> = DataErrorTuple<T, null>;

/**
* Represents a failure result where `error` contains an error instance and `data` is `null`.
*/
export type Failure<E extends Error> = DataErrorTuple<null, E | Error>;

/**
* Represents the result of an operation that can either succeed with `T` or fail with `E`.
*/
export type Result<T, E extends Error> = Success<T> | Failure<E>;

type TryCatchResult<T, E> = T extends Promise<infer U>
/**
* Resolves the return type based on whether `T` is a promise:
* - If `T` is a `Promise<U>`, returns `Promise<Result<U, E>>`.
* - Otherwise, returns `Result<T, E>`.
*/
export type TryCatchResult<T, E extends Error> = T extends Promise<infer U>
? Promise<Result<U, E>>
: Result<T, E>;

type TryCatchFunc<E_ extends Error = never> = <T, E extends Error = E_>(
fn?: T | (() => T),
/**
* Function type for handling try-catch logic.
*
* @template E_ Default error type.
* @template T The return type of the function being executed.
* @template E The error type that extends the default error type.
*
* @param fn A function, promise, or value to execute within a try-catch block.
* @param operationName Optional name added to `error.message` for better debugging and context.
*/
export type TryCatchFunc<E_ extends Error = Error> = <T, E extends Error = E_>(
fn: T | (() => T),
operationName?: string,
) => TryCatchResult<T, E>;

type TryCatch<
/**
* A utility for handling synchronous and asynchronous operations within a try-catch block.
*
* @template F The function type for try-catch execution.
* @template E_ The base error type.
*/
export type TryCatch<
F extends TryCatchFunc = TryCatchFunc,
E_ extends Error = never,
E_ extends Error = Error,
> = F & {
/**
* Executes a synchronous function inside a try-catch block.
*
* @param fn The function to execute.
* @param operationName Optional name added to `error.message` for better debugging and context.
* @returns A `Result<T, E>` indicating success or failure.
*/
sync: <T, E extends Error = E_>(
fn: () => T,
operationName?: string,
) => Result<T, E>;

/**
* Executes an asynchronous function inside a try-catch block.
*
* @param fn The function or promise to execute.
* @param operationName Optional name added to `error.message` for better debugging and context.
* @returns A `Promise<Result<T, E>>` indicating success or failure.
*/
async: <T, E extends Error = E_>(
fn: Promise<T> | (() => Promise<T>),
operationName?: string,
) => Promise<Result<T, E>>;

/**
* Creates a new `TryCatch` instance that handles additional error types.
*
* @template E Extends the existing error type.
* @returns A new `TryCatch` instance with extended error handling capabilities.
*/
errors: <E extends Error>() => TryCatch<TryCatchFunc<E | E_>, E | E_>;
};

/**
* tryCatch - Error handling that can be synchronous or asynchronous
* based on the input function.
*
* @param fn Function to execute, Promise or value.
* @param operationName Optional name for context.
* @param fn A function, promise, or value to execute within a try-catch block.
* @param operationName Optional name added to `error.message` for better debugging and context.
* @returns A Result, or a Promise resolving to a Result, depending on fn.
*/
export const tryCatch: TryCatch = <T, E extends Error = never>(
fn?: T | (() => T),
export const tryCatch: TryCatch = <T, E extends Error = Error>(
fn: T | (() => T),
operationName?: string,
) => {
try {
Expand All @@ -51,7 +113,7 @@ export const tryCatch: TryCatch = <T, E extends Error = never>(
}
};

export const tryCatchSync: TryCatch["sync"] = <T, E extends Error = never>(
export const tryCatchSync: TryCatch["sync"] = <T, E extends Error = Error>(
fn: () => T,
operationName?: string,
) => {
Expand All @@ -65,7 +127,7 @@ export const tryCatchSync: TryCatch["sync"] = <T, E extends Error = never>(

export const tryCatchAsync: TryCatch["async"] = async <
T,
E extends Error = never,
E extends Error = Error,
>(
fn: Promise<T> | (() => Promise<T>),
operationName?: string,
Expand Down
3 changes: 2 additions & 1 deletion packages/try-catch-tuple/tests/tryCatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,8 @@ describe("tryCatch", () => {

describe("edge cases", () => {
test("should handle undefined fn", () => {
const [result, error] = tryCatch();
const [result, error] = tryCatch(undefined);
if (error) expect.unreachable();
expect(result).toBe(undefined);
expect(error).toBeNil();
});
Expand Down