wellcrafted 0.16.1 → 0.18.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/README.md +6 -4
- package/dist/error/index.d.ts +83 -3
- package/dist/error/index.d.ts.map +1 -1
- package/dist/error/index.js +51 -1
- package/dist/error/index.js.map +1 -1
- package/dist/result/index.d.ts +3 -430
- package/dist/result/index.d.ts.map +1 -1
- package/dist/result/index.js +1 -332
- package/dist/result/index.js.map +1 -1
- package/dist/result-Bi5hwqKw.d.ts +431 -0
- package/dist/result-Bi5hwqKw.d.ts.map +1 -0
- package/dist/result-DxmXBFi5.js +335 -0
- package/dist/result-DxmXBFi5.js.map +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -208,11 +208,13 @@ Every `TaggedError` contains four essential properties that work together to cre
|
|
|
208
208
|
type TaggedError<T extends string> = {
|
|
209
209
|
readonly name: T; // 1. The discriminant
|
|
210
210
|
message: string; // 2. Human-readable description
|
|
211
|
-
context
|
|
212
|
-
cause
|
|
211
|
+
context?: Record<string, unknown>; // 3. Function inputs & debugging data (optional)
|
|
212
|
+
cause: unknown; // 4. Root cause
|
|
213
213
|
};
|
|
214
214
|
```
|
|
215
215
|
|
|
216
|
+
> The `context` property should include the function's input parameters and any relevant variables in the closure. If there are none, then it can be omitted. This creates a complete picture of what data led to the error, making debugging straightforward.
|
|
217
|
+
|
|
216
218
|
#### 1. **`name`** - The Discriminant (Tagged Field)
|
|
217
219
|
|
|
218
220
|
This is your error's unique identifier and the key to pattern matching. Use it in `if` statements and `switch` statements to handle different error types:
|
|
@@ -253,9 +255,9 @@ return Err({
|
|
|
253
255
|
});
|
|
254
256
|
```
|
|
255
257
|
|
|
256
|
-
#### 3. **`context`** - Debugging Data
|
|
258
|
+
#### 3. **`context`** - Function Inputs & Debugging Data
|
|
257
259
|
|
|
258
|
-
|
|
260
|
+
The primary purpose of `context` is to capture the function's input parameters, relevant variables in the closure, and additional context.
|
|
259
261
|
|
|
260
262
|
```ts
|
|
261
263
|
function processUser(id: number, options: UserOptions): Result<User, ProcessError> {
|
package/dist/error/index.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import { Err } from "../result-Bi5hwqKw.js";
|
|
2
|
+
|
|
1
3
|
//#region src/error/types.d.ts
|
|
4
|
+
|
|
2
5
|
/**
|
|
3
6
|
* Base error structure for all errors in the Result system.
|
|
4
7
|
*
|
|
@@ -18,7 +21,7 @@
|
|
|
18
21
|
type BaseError = Readonly<{
|
|
19
22
|
name: string;
|
|
20
23
|
message: string;
|
|
21
|
-
context
|
|
24
|
+
context?: Record<string, unknown>;
|
|
22
25
|
cause: unknown;
|
|
23
26
|
}>;
|
|
24
27
|
/**
|
|
@@ -54,6 +57,18 @@ type BaseError = Readonly<{
|
|
|
54
57
|
* }
|
|
55
58
|
* return Ok(input);
|
|
56
59
|
* }
|
|
60
|
+
*
|
|
61
|
+
* // Context is optional - omit when not needed:
|
|
62
|
+
* function checkAuth(): Result<User, AuthError> {
|
|
63
|
+
* if (!isAuthenticated) {
|
|
64
|
+
* return Err({
|
|
65
|
+
* name: "AuthError",
|
|
66
|
+
* message: "User not authenticated",
|
|
67
|
+
* cause: null,
|
|
68
|
+
* });
|
|
69
|
+
* }
|
|
70
|
+
* return Ok(currentUser);
|
|
71
|
+
* }
|
|
57
72
|
* ```
|
|
58
73
|
*/
|
|
59
74
|
type TaggedError<T extends string> = BaseError & {
|
|
@@ -98,7 +113,72 @@ type TaggedError<T extends string> = BaseError & {
|
|
|
98
113
|
* ```
|
|
99
114
|
*/
|
|
100
115
|
declare function extractErrorMessage(error: unknown): string;
|
|
101
|
-
|
|
116
|
+
/**
|
|
117
|
+
* Input type for creating a tagged error (everything except the name)
|
|
118
|
+
*/
|
|
119
|
+
type TaggedErrorWithoutName<T extends string> = Omit<TaggedError<T>, "name">;
|
|
120
|
+
/**
|
|
121
|
+
* Replaces the "Error" suffix with "Err" suffix in error type names.
|
|
122
|
+
*
|
|
123
|
+
* This utility type is used to create companion function names for error constructors
|
|
124
|
+
* that return Err-wrapped results, maintaining consistent naming conventions.
|
|
125
|
+
*
|
|
126
|
+
* @template T - An error type name that must end with "Error"
|
|
127
|
+
* @returns The type name with "Error" replaced by "Err"
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```ts
|
|
131
|
+
* type NetworkErr = ReplaceErrorWithErr<"NetworkError">; // "NetworkErr"
|
|
132
|
+
* type ValidationErr = ReplaceErrorWithErr<"ValidationError">; // "ValidationErr"
|
|
133
|
+
* type AuthErr = ReplaceErrorWithErr<"AuthError">; // "AuthErr"
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
type ReplaceErrorWithErr<T extends `${string}Error`> = T extends `${infer TBase}Error` ? `${TBase}Err` : never;
|
|
137
|
+
/**
|
|
138
|
+
* Return type for createTaggedError - contains both factory functions.
|
|
139
|
+
*
|
|
140
|
+
* Provides two factory functions:
|
|
141
|
+
* - One that creates plain TaggedError objects (named with "Error" suffix)
|
|
142
|
+
* - One that creates Err-wrapped TaggedError objects (named with "Err" suffix)
|
|
143
|
+
*/
|
|
144
|
+
type TaggedErrorFactories<TErrorName extends `${string}Error`> = { [K in TErrorName]: (input: TaggedErrorWithoutName<K>) => TaggedError<K> } & { [K in ReplaceErrorWithErr<TErrorName>]: (input: TaggedErrorWithoutName<TErrorName>) => Err<TaggedError<TErrorName>> };
|
|
145
|
+
/**
|
|
146
|
+
* Returns two different factory functions for tagged errors.
|
|
147
|
+
*
|
|
148
|
+
* Given an error name like "NetworkError", this returns:
|
|
149
|
+
* - `NetworkError`: Creates a plain TaggedError object
|
|
150
|
+
* - `NetworkErr`: Creates a TaggedError object wrapped in an Err result
|
|
151
|
+
*
|
|
152
|
+
* The naming pattern automatically replaces the "Error" suffix with "Err" suffix
|
|
153
|
+
* for the Result-wrapped version.
|
|
154
|
+
*
|
|
155
|
+
* @param name - The name of the error type (must end with "Error")
|
|
156
|
+
* @returns An object with two factory functions:
|
|
157
|
+
* - [name]: Function that creates plain TaggedError objects
|
|
158
|
+
* - [name with "Error" replaced by "Err"]: Function that creates Err-wrapped TaggedError objects
|
|
159
|
+
*
|
|
160
|
+
* @example
|
|
161
|
+
* ```ts
|
|
162
|
+
* const { NetworkError, NetworkErr } = createTaggedError('NetworkError');
|
|
163
|
+
*
|
|
164
|
+
* // NetworkError: Creates just the error object
|
|
165
|
+
* const error = NetworkError({
|
|
166
|
+
* message: 'Connection failed',
|
|
167
|
+
* context: { url: 'https://api.example.com' },
|
|
168
|
+
* cause: undefined
|
|
169
|
+
* });
|
|
170
|
+
* // Returns: { name: 'NetworkError', message: 'Connection failed', ... }
|
|
171
|
+
*
|
|
172
|
+
* // NetworkErr: Creates error and wraps in Err result
|
|
173
|
+
* return NetworkErr({
|
|
174
|
+
* message: 'Connection failed',
|
|
175
|
+
* context: { url: 'https://api.example.com' },
|
|
176
|
+
* cause: undefined
|
|
177
|
+
* });
|
|
178
|
+
* // Returns: Err({ name: 'NetworkError', message: 'Connection failed', ... })
|
|
179
|
+
* ```
|
|
180
|
+
*/
|
|
181
|
+
declare function createTaggedError<TErrorName extends `${string}Error`>(name: TErrorName): TaggedErrorFactories<TErrorName>;
|
|
102
182
|
//#endregion
|
|
103
|
-
export { BaseError, TaggedError, extractErrorMessage };
|
|
183
|
+
export { BaseError, TaggedError, createTaggedError, extractErrorMessage };
|
|
104
184
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/error/types.ts","../../src/error/utils.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/error/types.ts","../../src/error/utils.ts"],"sourcesContent":[],"mappings":";;;;;;;AAgBA;;;;AAAgC;AAsDhC;;;;AACiB;;;;ACjCD,KDtBJ,SAAA,GAAY,QCsBW,CAAA;EAoC9B,IAAA,EAAA,MAAA;EAAsB,OAAA,EAAA,MAAA;EAAA,OAAsC,CAAA,EDvDtD,MCuDsD,CAAA,MAAA,EAAA,OAAA,CAAA;EAAC,KAAb,EAAA,OAAA;CAAW,CAAA;AAAZ;AAAA;;;;AAmBT;AAAA;;;;;;;;;;;;;;AAclC;AAuCT;;;;;AAEuB;;;;;;;;;;;;;;;;;;;;;KD9EX,gCAAgC;iBAC5B;;;;;;AAvDhB;;;;AAAgC;AAsDhC;;;;AACiB;;;;ACjCjB;AA+BC;;;;;AAKmD;AAAA;;;;AAmBT;AAAA;;;;;;;;;AAaX,iBApEhB,mBAAA,CAoEgB,KAAA,EAAA,OAAA,CAAA,EAAA,MAAA;;;;KAhC3B,sBAiCC,CAAA,UAAA,MAAA,CAAA,GAjC0C,IAiC1C,CAjC+C,WAiC/C,CAjC2D,CAiC3D,CAAA,EAAA,MAAA,CAAA;AAAG;AAuCT;;;;;AAEuB;;;;;;;;;;KAxDlB,kDACJ,qCAAqC;;;;;;;;KASjC,oEACE,qBAAqB,uBAAuB,OAAO,YAAY,eAE/D,oBAAoB,sBAClB,uBAAuB,gBAC1B,IAAI,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAuCN,6DACT,aACJ,qBAAqB"}
|
package/dist/error/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { Err } from "../result-DxmXBFi5.js";
|
|
2
|
+
|
|
1
3
|
//#region src/error/utils.ts
|
|
2
4
|
/**
|
|
3
5
|
* Extracts a readable error message from an unknown error value
|
|
@@ -50,7 +52,55 @@ function extractErrorMessage(error) {
|
|
|
50
52
|
}
|
|
51
53
|
return String(error);
|
|
52
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* Returns two different factory functions for tagged errors.
|
|
57
|
+
*
|
|
58
|
+
* Given an error name like "NetworkError", this returns:
|
|
59
|
+
* - `NetworkError`: Creates a plain TaggedError object
|
|
60
|
+
* - `NetworkErr`: Creates a TaggedError object wrapped in an Err result
|
|
61
|
+
*
|
|
62
|
+
* The naming pattern automatically replaces the "Error" suffix with "Err" suffix
|
|
63
|
+
* for the Result-wrapped version.
|
|
64
|
+
*
|
|
65
|
+
* @param name - The name of the error type (must end with "Error")
|
|
66
|
+
* @returns An object with two factory functions:
|
|
67
|
+
* - [name]: Function that creates plain TaggedError objects
|
|
68
|
+
* - [name with "Error" replaced by "Err"]: Function that creates Err-wrapped TaggedError objects
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```ts
|
|
72
|
+
* const { NetworkError, NetworkErr } = createTaggedError('NetworkError');
|
|
73
|
+
*
|
|
74
|
+
* // NetworkError: Creates just the error object
|
|
75
|
+
* const error = NetworkError({
|
|
76
|
+
* message: 'Connection failed',
|
|
77
|
+
* context: { url: 'https://api.example.com' },
|
|
78
|
+
* cause: undefined
|
|
79
|
+
* });
|
|
80
|
+
* // Returns: { name: 'NetworkError', message: 'Connection failed', ... }
|
|
81
|
+
*
|
|
82
|
+
* // NetworkErr: Creates error and wraps in Err result
|
|
83
|
+
* return NetworkErr({
|
|
84
|
+
* message: 'Connection failed',
|
|
85
|
+
* context: { url: 'https://api.example.com' },
|
|
86
|
+
* cause: undefined
|
|
87
|
+
* });
|
|
88
|
+
* // Returns: Err({ name: 'NetworkError', message: 'Connection failed', ... })
|
|
89
|
+
* ```
|
|
90
|
+
*/
|
|
91
|
+
function createTaggedError(name) {
|
|
92
|
+
const errorConstructor = (error) => ({
|
|
93
|
+
...error,
|
|
94
|
+
name
|
|
95
|
+
});
|
|
96
|
+
const errName = name.replace(/Error$/, "Err");
|
|
97
|
+
const errConstructor = (error) => Err(errorConstructor(error));
|
|
98
|
+
return {
|
|
99
|
+
[name]: errorConstructor,
|
|
100
|
+
[errName]: errConstructor
|
|
101
|
+
};
|
|
102
|
+
}
|
|
53
103
|
|
|
54
104
|
//#endregion
|
|
55
|
-
export { extractErrorMessage };
|
|
105
|
+
export { createTaggedError, extractErrorMessage };
|
|
56
106
|
//# sourceMappingURL=index.js.map
|
package/dist/error/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["error: unknown"],"sources":["../../src/error/utils.ts"],"sourcesContent":["/**\n * Extracts a readable error message from an unknown error value\n *\n * This utility is commonly used in mapError functions when converting\n * unknown errors to typed error objects in the Result system.\n *\n * @param error - The unknown error to extract a message from\n * @returns A string representation of the error\n *\n * @example\n * ```ts\n * // With native Error\n * const error = new Error(\"Something went wrong\");\n * const message = extractErrorMessage(error); // \"Something went wrong\"\n *\n * // With string error\n * const stringError = \"String error\";\n * const message2 = extractErrorMessage(stringError); // \"String error\"\n *\n * // With object error\n * const unknownError = { code: 500, details: \"Server error\" };\n * const message3 = extractErrorMessage(unknownError); // '{\"code\":500,\"details\":\"Server error\"}'\n *\n * // Used in mapError function\n * const result = await tryAsync({\n * try: () => riskyOperation(),\n * mapError: (error): NetworkError => ({\n * name: \"NetworkError\",\n * message: extractErrorMessage(error),\n * context: { operation: \"riskyOperation\" },\n * cause: error,\n * }),\n * });\n * ```\n */\nexport function extractErrorMessage(error: unknown): string {\n\tif (error instanceof Error) {\n\t\treturn error.message;\n\t}\n\n\tif (typeof error === \"string\") {\n\t\treturn error;\n\t}\n\n\tif (typeof error === \"object\" && error !== null) {\n\t\t// Check for common error properties\n\t\tconst errorObj = error as Record<string, unknown>;\n\t\tif (typeof errorObj.message === \"string\") {\n\t\t\treturn errorObj.message;\n\t\t}\n\t\tif (typeof errorObj.error === \"string\") {\n\t\t\treturn errorObj.error;\n\t\t}\n\t\tif (typeof errorObj.description === \"string\") {\n\t\t\treturn errorObj.description;\n\t\t}\n\n\t\t// Fallback to JSON stringification\n\t\ttry {\n\t\t\treturn JSON.stringify(error);\n\t\t} catch {\n\t\t\treturn String(error);\n\t\t}\n\t}\n\n\treturn String(error);\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":["error: unknown","name: TErrorName","error: TaggedErrorWithoutName<TErrorName>"],"sources":["../../src/error/utils.ts"],"sourcesContent":["import type { TaggedError } from \"./types.js\";\nimport { Err } from \"../result/result.js\";\n\n/**\n * Extracts a readable error message from an unknown error value\n *\n * This utility is commonly used in mapError functions when converting\n * unknown errors to typed error objects in the Result system.\n *\n * @param error - The unknown error to extract a message from\n * @returns A string representation of the error\n *\n * @example\n * ```ts\n * // With native Error\n * const error = new Error(\"Something went wrong\");\n * const message = extractErrorMessage(error); // \"Something went wrong\"\n *\n * // With string error\n * const stringError = \"String error\";\n * const message2 = extractErrorMessage(stringError); // \"String error\"\n *\n * // With object error\n * const unknownError = { code: 500, details: \"Server error\" };\n * const message3 = extractErrorMessage(unknownError); // '{\"code\":500,\"details\":\"Server error\"}'\n *\n * // Used in mapError function\n * const result = await tryAsync({\n * try: () => riskyOperation(),\n * mapError: (error): NetworkError => ({\n * name: \"NetworkError\",\n * message: extractErrorMessage(error),\n * context: { operation: \"riskyOperation\" },\n * cause: error,\n * }),\n * });\n * ```\n */\nexport function extractErrorMessage(error: unknown): string {\n\tif (error instanceof Error) {\n\t\treturn error.message;\n\t}\n\n\tif (typeof error === \"string\") {\n\t\treturn error;\n\t}\n\n\tif (typeof error === \"object\" && error !== null) {\n\t\t// Check for common error properties\n\t\tconst errorObj = error as Record<string, unknown>;\n\t\tif (typeof errorObj.message === \"string\") {\n\t\t\treturn errorObj.message;\n\t\t}\n\t\tif (typeof errorObj.error === \"string\") {\n\t\t\treturn errorObj.error;\n\t\t}\n\t\tif (typeof errorObj.description === \"string\") {\n\t\t\treturn errorObj.description;\n\t\t}\n\n\t\t// Fallback to JSON stringification\n\t\ttry {\n\t\t\treturn JSON.stringify(error);\n\t\t} catch {\n\t\t\treturn String(error);\n\t\t}\n\t}\n\n\treturn String(error);\n}\n\n/**\n * Input type for creating a tagged error (everything except the name)\n */\ntype TaggedErrorWithoutName<T extends string> = Omit<TaggedError<T>, \"name\">;\n\n/**\n * Replaces the \"Error\" suffix with \"Err\" suffix in error type names.\n *\n * This utility type is used to create companion function names for error constructors\n * that return Err-wrapped results, maintaining consistent naming conventions.\n *\n * @template T - An error type name that must end with \"Error\"\n * @returns The type name with \"Error\" replaced by \"Err\"\n *\n * @example\n * ```ts\n * type NetworkErr = ReplaceErrorWithErr<\"NetworkError\">; // \"NetworkErr\"\n * type ValidationErr = ReplaceErrorWithErr<\"ValidationError\">; // \"ValidationErr\"\n * type AuthErr = ReplaceErrorWithErr<\"AuthError\">; // \"AuthErr\"\n * ```\n */\ntype ReplaceErrorWithErr<T extends `${string}Error`> =\n\tT extends `${infer TBase}Error` ? `${TBase}Err` : never;\n\n/**\n * Return type for createTaggedError - contains both factory functions.\n *\n * Provides two factory functions:\n * - One that creates plain TaggedError objects (named with \"Error\" suffix)\n * - One that creates Err-wrapped TaggedError objects (named with \"Err\" suffix)\n */\ntype TaggedErrorFactories<TErrorName extends `${string}Error`> = {\n\t[K in TErrorName]: (input: TaggedErrorWithoutName<K>) => TaggedError<K>;\n} & {\n\t[K in ReplaceErrorWithErr<TErrorName>]: (\n\t\tinput: TaggedErrorWithoutName<TErrorName>,\n\t) => Err<TaggedError<TErrorName>>;\n};\n\n/**\n * Returns two different factory functions for tagged errors.\n *\n * Given an error name like \"NetworkError\", this returns:\n * - `NetworkError`: Creates a plain TaggedError object\n * - `NetworkErr`: Creates a TaggedError object wrapped in an Err result\n *\n * The naming pattern automatically replaces the \"Error\" suffix with \"Err\" suffix\n * for the Result-wrapped version.\n *\n * @param name - The name of the error type (must end with \"Error\")\n * @returns An object with two factory functions:\n * - [name]: Function that creates plain TaggedError objects\n * - [name with \"Error\" replaced by \"Err\"]: Function that creates Err-wrapped TaggedError objects\n *\n * @example\n * ```ts\n * const { NetworkError, NetworkErr } = createTaggedError('NetworkError');\n *\n * // NetworkError: Creates just the error object\n * const error = NetworkError({\n * message: 'Connection failed',\n * context: { url: 'https://api.example.com' },\n * cause: undefined\n * });\n * // Returns: { name: 'NetworkError', message: 'Connection failed', ... }\n *\n * // NetworkErr: Creates error and wraps in Err result\n * return NetworkErr({\n * message: 'Connection failed',\n * context: { url: 'https://api.example.com' },\n * cause: undefined\n * });\n * // Returns: Err({ name: 'NetworkError', message: 'Connection failed', ... })\n * ```\n */\nexport function createTaggedError<TErrorName extends `${string}Error`>(\n\tname: TErrorName,\n): TaggedErrorFactories<TErrorName> {\n\tconst errorConstructor = (\n\t\terror: TaggedErrorWithoutName<TErrorName>,\n\t): TaggedError<TErrorName> => ({ ...error, name }) as TaggedError<TErrorName>;\n\n\tconst errName = name.replace(\n\t\t/Error$/,\n\t\t\"Err\",\n\t) as ReplaceErrorWithErr<TErrorName>;\n\tconst errConstructor = (error: TaggedErrorWithoutName<TErrorName>) =>\n\t\tErr(errorConstructor(error));\n\n\treturn {\n\t\t[name]: errorConstructor,\n\t\t[errName]: errConstructor,\n\t} as TaggedErrorFactories<TErrorName>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,oBAAoBA,OAAwB;AAC3D,KAAI,iBAAiB,MACpB,QAAO,MAAM;AAGd,YAAW,UAAU,SACpB,QAAO;AAGR,YAAW,UAAU,YAAY,UAAU,MAAM;EAEhD,MAAM,WAAW;AACjB,aAAW,SAAS,YAAY,SAC/B,QAAO,SAAS;AAEjB,aAAW,SAAS,UAAU,SAC7B,QAAO,SAAS;AAEjB,aAAW,SAAS,gBAAgB,SACnC,QAAO,SAAS;AAIjB,MAAI;AACH,UAAO,KAAK,UAAU,MAAM;EAC5B,QAAO;AACP,UAAO,OAAO,MAAM;EACpB;CACD;AAED,QAAO,OAAO,MAAM;AACpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ED,SAAgB,kBACfC,MACmC;CACnC,MAAM,mBAAmB,CACxBC,WAC8B;EAAE,GAAG;EAAO;CAAM;CAEjD,MAAM,UAAU,KAAK,QACpB,UACA,MACA;CACD,MAAM,iBAAiB,CAACA,UACvB,IAAI,iBAAiB,MAAM,CAAC;AAE7B,QAAO;GACL,OAAO;GACP,UAAU;CACX;AACD"}
|
package/dist/result/index.d.ts
CHANGED
|
@@ -1,433 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* Represents the successful outcome of an operation, encapsulating the success value.
|
|
4
|
-
*
|
|
5
|
-
* This is the 'Ok' variant of the `Result` type. It holds a `data` property
|
|
6
|
-
* of type `T` (the success value) and an `error` property explicitly set to `null`,
|
|
7
|
-
* signifying no error occurred.
|
|
8
|
-
*
|
|
9
|
-
* Use this type in conjunction with `Err<E>` and `Result<T, E>`.
|
|
10
|
-
*
|
|
11
|
-
* @template T - The type of the success value contained within.
|
|
12
|
-
*/
|
|
13
|
-
type Ok<T> = {
|
|
14
|
-
data: T;
|
|
15
|
-
error: null;
|
|
16
|
-
};
|
|
17
|
-
/**
|
|
18
|
-
* Represents the failure outcome of an operation, encapsulating the error value.
|
|
19
|
-
*
|
|
20
|
-
* This is the 'Err' variant of the `Result` type. It holds an `error` property
|
|
21
|
-
* of type `E` (the error value) and a `data` property explicitly set to `null`,
|
|
22
|
-
* signifying that no success value is present due to the failure.
|
|
23
|
-
*
|
|
24
|
-
* Use this type in conjunction with `Ok<T>` and `Result<T, E>`.
|
|
25
|
-
*
|
|
26
|
-
* @template E - The type of the error value contained within.
|
|
27
|
-
*/
|
|
28
|
-
type Err<E> = {
|
|
29
|
-
error: E;
|
|
30
|
-
data: null;
|
|
31
|
-
};
|
|
32
|
-
/**
|
|
33
|
-
* A type that represents the outcome of an operation that can either succeed or fail.
|
|
34
|
-
*
|
|
35
|
-
* `Result<T, E>` is a discriminated union type with two possible variants:
|
|
36
|
-
* - `Ok<T>`: Represents a successful outcome, containing a `data` field with the success value of type `T`.
|
|
37
|
-
* In this case, the `error` field is `null`.
|
|
38
|
-
* - `Err<E>`: Represents a failure outcome, containing an `error` field with the error value of type `E`.
|
|
39
|
-
* In this case, the `data` field is `null`.
|
|
40
|
-
*
|
|
41
|
-
* This type promotes explicit error handling by requiring developers to check
|
|
42
|
-
* the variant of the `Result` before accessing its potential value or error.
|
|
43
|
-
* It helps avoid runtime errors often associated with implicit error handling (e.g., relying on `try-catch` for all errors).
|
|
44
|
-
*
|
|
45
|
-
* @template T - The type of the success value if the operation is successful (held in `Ok<T>`).
|
|
46
|
-
* @template E - The type of the error value if the operation fails (held in `Err<E>`).
|
|
47
|
-
* @example
|
|
48
|
-
* ```ts
|
|
49
|
-
* function divide(numerator: number, denominator: number): Result<number, string> {
|
|
50
|
-
* if (denominator === 0) {
|
|
51
|
-
* return Err("Cannot divide by zero");
|
|
52
|
-
* }
|
|
53
|
-
* return Ok(numerator / denominator);
|
|
54
|
-
* }
|
|
55
|
-
*
|
|
56
|
-
* const result1 = divide(10, 2);
|
|
57
|
-
* if (isOk(result1)) {
|
|
58
|
-
* console.log("Success:", result1.data); // Output: Success: 5
|
|
59
|
-
* }
|
|
60
|
-
*
|
|
61
|
-
* const result2 = divide(10, 0);
|
|
62
|
-
* if (isErr(result2)) {
|
|
63
|
-
* console.error("Failure:", result2.error); // Output: Failure: Cannot divide by zero
|
|
64
|
-
* }
|
|
65
|
-
* ```
|
|
66
|
-
*/
|
|
67
|
-
type Result<T, E> = Ok<T> | Err<E>;
|
|
68
|
-
/**
|
|
69
|
-
* Constructs an `Ok<T>` variant, representing a successful outcome.
|
|
70
|
-
*
|
|
71
|
-
* This factory function creates the success variant of a `Result`.
|
|
72
|
-
* It wraps the provided `data` (the success value) and ensures the `error` property is `null`.
|
|
73
|
-
*
|
|
74
|
-
* @template T - The type of the success value.
|
|
75
|
-
* @param data - The success value to be wrapped in the `Ok` variant.
|
|
76
|
-
* @returns An `Ok<T>` object with the provided data and `error` set to `null`.
|
|
77
|
-
* @example
|
|
78
|
-
* ```ts
|
|
79
|
-
* const successfulResult = Ok("Operation completed successfully");
|
|
80
|
-
* // successfulResult is { data: "Operation completed successfully", error: null }
|
|
81
|
-
* ```
|
|
82
|
-
*/
|
|
83
|
-
declare const Ok: <T>(data: T) => Ok<T>;
|
|
84
|
-
/**
|
|
85
|
-
* Constructs an `Err<E>` variant, representing a failure outcome.
|
|
86
|
-
*
|
|
87
|
-
* This factory function creates the error variant of a `Result`.
|
|
88
|
-
* It wraps the provided `error` (the error value) and ensures the `data` property is `null`.
|
|
89
|
-
*
|
|
90
|
-
* @template E - The type of the error value.
|
|
91
|
-
* @param error - The error value to be wrapped in the `Err` variant. This value represents the specific error that occurred.
|
|
92
|
-
* @returns An `Err<E>` object with the provided error and `data` set to `null`.
|
|
93
|
-
* @example
|
|
94
|
-
* ```ts
|
|
95
|
-
* const failedResult = Err(new TypeError("Invalid input"));
|
|
96
|
-
* // failedResult is { error: TypeError("Invalid input"), data: null }
|
|
97
|
-
* ```
|
|
98
|
-
*/
|
|
99
|
-
declare const Err: <E>(error: E) => Err<E>;
|
|
100
|
-
/**
|
|
101
|
-
* Utility type to extract the `Ok<T>` variant from a `Result<T, E>` union type.
|
|
102
|
-
*
|
|
103
|
-
* If `R` is a `Result` type (e.g., `Result<string, Error>`), this type will resolve
|
|
104
|
-
* to `Ok<string>`. This can be useful in generic contexts or for type narrowing.
|
|
105
|
-
*
|
|
106
|
-
* @template R - The `Result<T, E>` union type from which to extract the `Ok<T>` variant.
|
|
107
|
-
* Must extend `Result<unknown, unknown>`.
|
|
108
|
-
*/
|
|
109
|
-
type ExtractOkFromResult<R extends Result<unknown, unknown>> = Extract<R, {
|
|
110
|
-
error: null;
|
|
111
|
-
}>;
|
|
112
|
-
/**
|
|
113
|
-
* Utility type to extract the `Err<E>` variant from a `Result<T, E>` union type.
|
|
114
|
-
*
|
|
115
|
-
* If `R` is a `Result` type (e.g., `Result<string, Error>`), this type will resolve
|
|
116
|
-
* to `Err<Error>`. This can be useful in generic contexts or for type narrowing.
|
|
117
|
-
*
|
|
118
|
-
* @template R - The `Result<T, E>` union type from which to extract the `Err<E>` variant.
|
|
119
|
-
* Must extend `Result<unknown, unknown>`.
|
|
120
|
-
*/
|
|
121
|
-
type ExtractErrFromResult<R extends Result<unknown, unknown>> = Extract<R, {
|
|
122
|
-
data: null;
|
|
123
|
-
}>;
|
|
124
|
-
/**
|
|
125
|
-
* Utility type to extract the success value's type `T` from a `Result<T, E>` type.
|
|
126
|
-
*
|
|
127
|
-
* If `R` is an `Ok<T>` variant (or a `Result<T, E>` that could be an `Ok<T>`),
|
|
128
|
-
* this type resolves to `T`. If `R` can only be an `Err<E>` variant, it resolves to `never`.
|
|
129
|
-
* This is useful for obtaining the type of the `data` field when you know you have a success.
|
|
130
|
-
*
|
|
131
|
-
* @template R - The `Result<T, E>` type from which to extract the success value's type.
|
|
132
|
-
* Must extend `Result<unknown, unknown>`.
|
|
133
|
-
* @example
|
|
134
|
-
* ```ts
|
|
135
|
-
* type MyResult = Result<number, string>;
|
|
136
|
-
* type SuccessValueType = UnwrapOk<MyResult>; // SuccessValueType is number
|
|
137
|
-
*
|
|
138
|
-
* type MyErrorResult = Err<string>;
|
|
139
|
-
* type ErrorValueType = UnwrapOk<MyErrorResult>; // ErrorValueType is never
|
|
140
|
-
* ```
|
|
141
|
-
*/
|
|
142
|
-
type UnwrapOk<R extends Result<unknown, unknown>> = R extends Ok<infer U> ? U : never;
|
|
143
|
-
/**
|
|
144
|
-
* Utility type to extract the error value's type `E` from a `Result<T, E>` type.
|
|
145
|
-
*
|
|
146
|
-
* If `R` is an `Err<E>` variant (or a `Result<T, E>` that could be an `Err<E>`),
|
|
147
|
-
* this type resolves to `E`. If `R` can only be an `Ok<T>` variant, it resolves to `never`.
|
|
148
|
-
* This is useful for obtaining the type of the `error` field when you know you have a failure.
|
|
149
|
-
*
|
|
150
|
-
* @template R - The `Result<T, E>` type from which to extract the error value's type.
|
|
151
|
-
* Must extend `Result<unknown, unknown>`.
|
|
152
|
-
* @example
|
|
153
|
-
* ```ts
|
|
154
|
-
* type MyResult = Result<number, string>;
|
|
155
|
-
* type ErrorValueType = UnwrapErr<MyResult>; // ErrorValueType is string
|
|
156
|
-
*
|
|
157
|
-
* type MySuccessResult = Ok<number>;
|
|
158
|
-
* type SuccessValueType = UnwrapErr<MySuccessResult>; // SuccessValueType is never
|
|
159
|
-
* ```
|
|
160
|
-
*/
|
|
161
|
-
type UnwrapErr<R extends Result<unknown, unknown>> = R extends Err<infer E> ? E : never;
|
|
162
|
-
/**
|
|
163
|
-
* Type guard to runtime check if an unknown value is a valid `Result<T, E>`.
|
|
164
|
-
*
|
|
165
|
-
* A value is considered a valid `Result` if:
|
|
166
|
-
* 1. It is a non-null object.
|
|
167
|
-
* 2. It has both `data` and `error` properties.
|
|
168
|
-
* 3. Exactly one of `data` or `error` is `null`. The other must be non-`null`.
|
|
169
|
-
*
|
|
170
|
-
* This function does not validate the types of `data` or `error` beyond `null` checks.
|
|
171
|
-
*
|
|
172
|
-
* @template T - The expected type of the success value if the value is an `Ok` variant (defaults to `unknown`).
|
|
173
|
-
* @template E - The expected type of the error value if the value is an `Err` variant (defaults to `unknown`).
|
|
174
|
-
* @param value - The value to check.
|
|
175
|
-
* @returns `true` if the value conforms to the `Result` structure, `false` otherwise.
|
|
176
|
-
* If `true`, TypeScript's type system will narrow `value` to `Result<T, E>`.
|
|
177
|
-
* @example
|
|
178
|
-
* ```ts
|
|
179
|
-
* declare const someValue: unknown;
|
|
180
|
-
*
|
|
181
|
-
* if (isResult<string, Error>(someValue)) {
|
|
182
|
-
* // someValue is now typed as Result<string, Error>
|
|
183
|
-
* if (isOk(someValue)) {
|
|
184
|
-
* console.log(someValue.data); // string
|
|
185
|
-
* } else {
|
|
186
|
-
* console.error(someValue.error); // Error
|
|
187
|
-
* }
|
|
188
|
-
* }
|
|
189
|
-
* ```
|
|
190
|
-
*/
|
|
191
|
-
declare function isResult<T = unknown, E = unknown>(value: unknown): value is Result<T, E>;
|
|
192
|
-
/**
|
|
193
|
-
* Type guard to runtime check if a `Result<T, E>` is an `Ok<T>` variant.
|
|
194
|
-
*
|
|
195
|
-
* This function narrows the type of a `Result` to `Ok<T>` if it represents a successful outcome.
|
|
196
|
-
* An `Ok<T>` variant is identified by its `error` property being `null`.
|
|
197
|
-
*
|
|
198
|
-
* @template T - The success value type.
|
|
199
|
-
* @template E - The error value type.
|
|
200
|
-
* @param result - The `Result<T, E>` to check.
|
|
201
|
-
* @returns `true` if the `result` is an `Ok<T>` variant, `false` otherwise.
|
|
202
|
-
* If `true`, TypeScript's type system will narrow `result` to `Ok<T>`.
|
|
203
|
-
* @example
|
|
204
|
-
* ```ts
|
|
205
|
-
* declare const myResult: Result<number, string>;
|
|
206
|
-
*
|
|
207
|
-
* if (isOk(myResult)) {
|
|
208
|
-
* // myResult is now typed as Ok<number>
|
|
209
|
-
* console.log("Success value:", myResult.data); // myResult.data is number
|
|
210
|
-
* }
|
|
211
|
-
* ```
|
|
212
|
-
*/
|
|
213
|
-
declare function isOk<T, E>(result: Result<T, E>): result is Ok<T>;
|
|
214
|
-
/**
|
|
215
|
-
* Type guard to runtime check if a `Result<T, E>` is an `Err<E>` variant.
|
|
216
|
-
*
|
|
217
|
-
* This function narrows the type of a `Result` to `Err<E>` if it represents a failure outcome.
|
|
218
|
-
* An `Err<E>` variant is identified by its `error` property being non-`null` (and thus `data` being `null`).
|
|
219
|
-
*
|
|
220
|
-
* @template T - The success value type.
|
|
221
|
-
* @template E - The error value type.
|
|
222
|
-
* @param result - The `Result<T, E>` to check.
|
|
223
|
-
* @returns `true` if the `result` is an `Err<E>` variant, `false` otherwise.
|
|
224
|
-
* If `true`, TypeScript's type system will narrow `result` to `Err<E>`.
|
|
225
|
-
* @example
|
|
226
|
-
* ```ts
|
|
227
|
-
* declare const myResult: Result<number, string>;
|
|
228
|
-
*
|
|
229
|
-
* if (isErr(myResult)) {
|
|
230
|
-
* // myResult is now typed as Err<string>
|
|
231
|
-
* console.error("Error value:", myResult.error); // myResult.error is string
|
|
232
|
-
* }
|
|
233
|
-
* ```
|
|
234
|
-
*/
|
|
235
|
-
declare function isErr<T, E>(result: Result<T, E>): result is Err<E>;
|
|
236
|
-
/**
|
|
237
|
-
* Executes a synchronous operation and wraps its outcome (success or failure) in a `Result<T, E>`.
|
|
238
|
-
*
|
|
239
|
-
* This function attempts to execute the `operation`.
|
|
240
|
-
* - If `operation` completes successfully, its return value is wrapped in an `Ok<T>` variant.
|
|
241
|
-
* - If `operation` throws an exception, the caught exception (of type `unknown`) is passed to
|
|
242
|
-
* the `mapError` function. `mapError` is responsible for transforming this `unknown`
|
|
243
|
-
* exception into a well-typed error value of type `E`. This error value is then wrapped
|
|
244
|
-
* in an `Err<E>` variant.
|
|
245
|
-
*
|
|
246
|
-
* @template T - The type of the success value returned by the `operation` if it succeeds.
|
|
247
|
-
* @template E - The type of the error value produced by `mapError` if the `operation` fails.
|
|
248
|
-
* @param options - An object containing the operation and error mapping function.
|
|
249
|
-
* @param options.try - The synchronous operation to execute. This function is expected to return a value of type `T`.
|
|
250
|
-
* @param options.mapError - A function that takes the `unknown` exception caught from `options.try`
|
|
251
|
-
* and transforms it into a specific error value of type `E`. This function
|
|
252
|
-
* is crucial for creating a well-typed error for the `Err<E>` variant.
|
|
253
|
-
* @returns A `Result<T, E>`: `Ok<T>` if `options.try` succeeds, or `Err<E>` if it throws and `options.mapError` provides an error value.
|
|
254
|
-
* @example
|
|
255
|
-
* ```ts
|
|
256
|
-
* function parseJson(jsonString: string): Result<object, SyntaxError> {
|
|
257
|
-
* return trySync({
|
|
258
|
-
* try: () => JSON.parse(jsonString),
|
|
259
|
-
* mapError: (err: unknown) => {
|
|
260
|
-
* if (err instanceof SyntaxError) return err;
|
|
261
|
-
* return new SyntaxError("Unknown parsing error");
|
|
262
|
-
* }
|
|
263
|
-
* });
|
|
264
|
-
* }
|
|
265
|
-
*
|
|
266
|
-
* const validResult = parseJson('{"name":"Result"}'); // Ok<{name: string}>
|
|
267
|
-
* const invalidResult = parseJson('invalid json'); // Err<SyntaxError>
|
|
268
|
-
*
|
|
269
|
-
* if (isOk(validResult)) console.log(validResult.data);
|
|
270
|
-
* if (isErr(invalidResult)) console.error(invalidResult.error.message);
|
|
271
|
-
* ```
|
|
272
|
-
*/
|
|
273
|
-
declare function trySync<T, E>({
|
|
274
|
-
try: operation,
|
|
275
|
-
mapError
|
|
276
|
-
}: {
|
|
277
|
-
try: () => T;
|
|
278
|
-
mapError: (error: unknown) => E;
|
|
279
|
-
}): Result<T, E>;
|
|
280
|
-
/**
|
|
281
|
-
* Executes an asynchronous operation (returning a `Promise`) and wraps its outcome in a `Promise<Result<T, E>>`.
|
|
282
|
-
*
|
|
283
|
-
* This function attempts to execute the asynchronous `operation`.
|
|
284
|
-
* - If the `Promise` returned by `operation` resolves successfully, its resolved value is wrapped in an `Ok<T>` variant.
|
|
285
|
-
* - If the `Promise` returned by `operation` rejects, or if `operation` itself throws an exception synchronously,
|
|
286
|
-
* the caught exception/rejection reason (of type `unknown`) is passed to the `mapError` function.
|
|
287
|
-
* `mapError` is responsible for transforming this `unknown` error into a well-typed error value of type `E`.
|
|
288
|
-
* This error value is then wrapped in an `Err<E>` variant.
|
|
289
|
-
*
|
|
290
|
-
* The entire outcome (`Ok<T>` or `Err<E>`) is wrapped in a `Promise`.
|
|
291
|
-
*
|
|
292
|
-
* @template T - The type of the success value the `Promise` from `operation` resolves to.
|
|
293
|
-
* @template E - The type of the error value produced by `mapError` if the `operation` fails or rejects.
|
|
294
|
-
* @param options - An object containing the asynchronous operation and error mapping function.
|
|
295
|
-
* @param options.try - The asynchronous operation to execute. This function must return a `Promise<T>`.
|
|
296
|
-
* @param options.mapError - A function that takes the `unknown` exception/rejection reason caught from `options.try`
|
|
297
|
-
* and transforms it into a specific error value of type `E`. This function
|
|
298
|
-
* is crucial for creating a well-typed error for the `Err<E>` variant.
|
|
299
|
-
* @returns A `Promise` that resolves to a `Result<T, E>`: `Ok<T>` if `options.try`'s `Promise` resolves,
|
|
300
|
-
* or `Err<E>` if it rejects/throws and `options.mapError` provides an error value.
|
|
301
|
-
* @example
|
|
302
|
-
* ```ts
|
|
303
|
-
* async function fetchData(url: string): Promise<Result<Response, Error>> {
|
|
304
|
-
* return tryAsync({
|
|
305
|
-
* try: async () => fetch(url),
|
|
306
|
-
* mapError: (err: unknown) => {
|
|
307
|
-
* if (err instanceof Error) return err;
|
|
308
|
-
* return new Error("Network request failed");
|
|
309
|
-
* }
|
|
310
|
-
* });
|
|
311
|
-
* }
|
|
312
|
-
*
|
|
313
|
-
* async function processData() {
|
|
314
|
-
* const result = await fetchData("/api/data");
|
|
315
|
-
* if (isOk(result)) {
|
|
316
|
-
* const response = result.data;
|
|
317
|
-
* console.log("Data fetched:", await response.json());
|
|
318
|
-
* } else {
|
|
319
|
-
* console.error("Fetch error:", result.error.message);
|
|
320
|
-
* }
|
|
321
|
-
* }
|
|
322
|
-
* processData();
|
|
323
|
-
* ```
|
|
324
|
-
*/
|
|
325
|
-
declare function tryAsync<T, E>({
|
|
326
|
-
try: operation,
|
|
327
|
-
mapError
|
|
328
|
-
}: {
|
|
329
|
-
try: () => Promise<T>;
|
|
330
|
-
mapError: (error: unknown) => E;
|
|
331
|
-
}): Promise<Result<T, E>>;
|
|
332
|
-
/**
|
|
333
|
-
* Resolves a value that may or may not be wrapped in a `Result`, returning the final value.
|
|
334
|
-
*
|
|
335
|
-
* This function handles the common pattern where a value might be a `Result<T, E>` or a plain `T`:
|
|
336
|
-
* - If `value` is an `Ok<T>` variant, returns the contained success value.
|
|
337
|
-
* - If `value` is an `Err<E>` variant, throws the contained error value.
|
|
338
|
-
* - If `value` is not a `Result` (i.e., it's already a plain value of type `T`),
|
|
339
|
-
* returns it as-is.
|
|
340
|
-
*
|
|
341
|
-
* This is useful when working with APIs that might return either direct values or Results,
|
|
342
|
-
* allowing you to normalize them to the actual value or propagate errors via throwing.
|
|
343
|
-
*
|
|
344
|
-
* Use `resolve` when the input might or might not be a Result.
|
|
345
|
-
* Use `unwrap` when you know the input is definitely a Result.
|
|
346
|
-
*
|
|
347
|
-
* @template T - The type of the success value (if `value` is `Ok<T>`) or the type of the plain value.
|
|
348
|
-
* @template E - The type of the error value (if `value` is `Err<E>`).
|
|
349
|
-
* @param value - The value to resolve. Can be a `Result<T, E>` or a plain value of type `T`.
|
|
350
|
-
* @returns The final value of type `T` if `value` is `Ok<T>` or if `value` is already a plain `T`.
|
|
351
|
-
* @throws The error value `E` if `value` is an `Err<E>` variant.
|
|
352
|
-
*
|
|
353
|
-
* @example
|
|
354
|
-
* ```ts
|
|
355
|
-
* // Example with an Ok variant
|
|
356
|
-
* const okResult = Ok("success data");
|
|
357
|
-
* const resolved = resolve(okResult); // "success data"
|
|
358
|
-
*
|
|
359
|
-
* // Example with an Err variant
|
|
360
|
-
* const errResult = Err(new Error("failure"));
|
|
361
|
-
* try {
|
|
362
|
-
* resolve(errResult);
|
|
363
|
-
* } catch (e) {
|
|
364
|
-
* console.error(e.message); // "failure"
|
|
365
|
-
* }
|
|
366
|
-
*
|
|
367
|
-
* // Example with a plain value
|
|
368
|
-
* const plainValue = "plain data";
|
|
369
|
-
* const resolved = resolve(plainValue); // "plain data"
|
|
370
|
-
*
|
|
371
|
-
* // Example with a function that might return Result or plain value
|
|
372
|
-
* declare function mightReturnResult(): string | Result<string, Error>;
|
|
373
|
-
* const outcome = mightReturnResult();
|
|
374
|
-
* try {
|
|
375
|
-
* const finalValue = resolve(outcome); // handles both cases
|
|
376
|
-
* console.log("Final value:", finalValue);
|
|
377
|
-
* } catch (e) {
|
|
378
|
-
* console.error("Operation failed:", e);
|
|
379
|
-
* }
|
|
380
|
-
* ```
|
|
381
|
-
*/
|
|
382
|
-
/**
|
|
383
|
-
* Unwraps a `Result<T, E>`, returning the success value or throwing the error.
|
|
384
|
-
*
|
|
385
|
-
* This function extracts the data from a `Result`:
|
|
386
|
-
* - If the `Result` is an `Ok<T>` variant, returns the contained success value of type `T`.
|
|
387
|
-
* - If the `Result` is an `Err<E>` variant, throws the contained error value of type `E`.
|
|
388
|
-
*
|
|
389
|
-
* Unlike `resolve`, this function expects the input to always be a `Result` type,
|
|
390
|
-
* making it more direct for cases where you know you're working with a `Result`.
|
|
391
|
-
*
|
|
392
|
-
* @template T - The type of the success value contained in the `Ok<T>` variant.
|
|
393
|
-
* @template E - The type of the error value contained in the `Err<E>` variant.
|
|
394
|
-
* @param result - The `Result<T, E>` to unwrap.
|
|
395
|
-
* @returns The success value of type `T` if the `Result` is `Ok<T>`.
|
|
396
|
-
* @throws The error value of type `E` if the `Result` is `Err<E>`.
|
|
397
|
-
*
|
|
398
|
-
* @example
|
|
399
|
-
* ```ts
|
|
400
|
-
* // Example with an Ok variant
|
|
401
|
-
* const okResult = Ok("success data");
|
|
402
|
-
* const value = unwrap(okResult); // "success data"
|
|
403
|
-
*
|
|
404
|
-
* // Example with an Err variant
|
|
405
|
-
* const errResult = Err(new Error("something went wrong"));
|
|
406
|
-
* try {
|
|
407
|
-
* unwrap(errResult);
|
|
408
|
-
* } catch (error) {
|
|
409
|
-
* console.error(error.message); // "something went wrong"
|
|
410
|
-
* }
|
|
411
|
-
*
|
|
412
|
-
* // Usage in a function that returns Result
|
|
413
|
-
* function divide(a: number, b: number): Result<number, string> {
|
|
414
|
-
* if (b === 0) return Err("Division by zero");
|
|
415
|
-
* return Ok(a / b);
|
|
416
|
-
* }
|
|
417
|
-
*
|
|
418
|
-
* try {
|
|
419
|
-
* const result = unwrap(divide(10, 2)); // 5
|
|
420
|
-
* console.log("Result:", result);
|
|
421
|
-
* } catch (error) {
|
|
422
|
-
* console.error("Division failed:", error);
|
|
423
|
-
* }
|
|
424
|
-
* ```
|
|
425
|
-
*/
|
|
426
|
-
declare function unwrap<T, E>(result: Result<T, E>): T;
|
|
427
|
-
declare function resolve<T, E>(value: T | Result<T, E>): T;
|
|
428
|
-
//# sourceMappingURL=result.d.ts.map
|
|
429
|
-
//#endregion
|
|
1
|
+
import { Err, ExtractErrFromResult, ExtractOkFromResult, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap } from "../result-Bi5hwqKw.js";
|
|
2
|
+
|
|
430
3
|
//#region src/result/utils.d.ts
|
|
4
|
+
|
|
431
5
|
/**
|
|
432
6
|
* Partitions an array of Result objects into two separate arrays based on their status.
|
|
433
7
|
*
|
|
@@ -449,7 +23,6 @@ declare function partitionResults<T, E>(results: Result<T, E>[]): {
|
|
|
449
23
|
errs: Err<E>[];
|
|
450
24
|
};
|
|
451
25
|
//# sourceMappingURL=utils.d.ts.map
|
|
452
|
-
|
|
453
26
|
//#endregion
|
|
454
27
|
export { Err, ExtractErrFromResult, ExtractOkFromResult, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, partitionResults, resolve, tryAsync, trySync, unwrap };
|
|
455
28
|
//# sourceMappingURL=index.d.ts.map
|