badlib 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "badlib",
3
- "version": "0.0.3",
3
+ "version": "0.1.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "exports": {
@@ -0,0 +1,25 @@
1
+ // Thanks Theo for this function.
2
+ // Source: https://gist.github.com/t3dotgg/a486c4ae66d32bf17c09c73609dacc5b
3
+
4
+ // Types for the result object with discriminated union
5
+ type Success<T> = {
6
+ data: T;
7
+ error: null;
8
+ };
9
+
10
+ type Failure<E> = {
11
+ data: null;
12
+ error: E;
13
+ };
14
+
15
+ type Result<T, E = Error> = Success<T> | Failure<E>;
16
+
17
+ // Main wrapper function
18
+ export async function tryCatch<T, E = Error>(promise: Promise<T>): Promise<Result<T, E>> {
19
+ try {
20
+ const data = await promise;
21
+ return { data, error: null };
22
+ } catch (error) {
23
+ return { data: null, error: error as E };
24
+ }
25
+ }