-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples.ts
More file actions
431 lines (362 loc) · 11.7 KB
/
Copy pathexamples.ts
File metadata and controls
431 lines (362 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/**
* Comprehensive examples demonstrating the fully typed error handling system
* Similar to neverthrow and Rust's Result type
*/
import type { Result } from './src/types'
import {
combine,
combineWithAllErrors,
err,
fromNullable,
ok,
traverse,
tryCatch,
tryCatchAsync,
} from './src/result'
// ============================================================================
// Example 1: Basic usage with type inference
// ============================================================================
function divideBasic(a: number, b: number): Result<number, string> {
if (b === 0) {
return err('Division by zero')
}
return ok(a / b)
}
// Type is inferred as Result<number, string>
const result1 = divideBasic(10, 2)
// Type narrowing works perfectly
if (result1.isOk) {
// eslint-disable-next-line no-console
console.log(result1.value) // Type: number
}
else {
// eslint-disable-next-line no-console
console.log(result1.error) // Type: string
}
// ============================================================================
// Example 2: Chaining operations with map and andThen
// ============================================================================
function parseNumber(input: string): Result<number, string> {
const num = Number.parseFloat(input)
return Number.isNaN(num) ? err('Invalid number') : ok(num)
}
function validatePositive(num: number): Result<number, string> {
return num > 0 ? ok(num) : err('Number must be positive')
}
function sqrt(num: number): Result<number, string> {
return num >= 0 ? ok(Math.sqrt(num)) : err('Cannot take square root of negative number')
}
// Chain operations with full type safety
// Example showing the power of chaining
parseNumber('16')
.andThen(validatePositive)
.andThen(sqrt)
.map(n => n * 2)
// ============================================================================
// Example 3: Pattern matching
// ============================================================================
interface User {
id: number
name: string
email: string
}
function findUser(id: number): Result<User, string> {
// Simulated database lookup
if (id === 1) {
return ok({ id: 1, name: 'Alice', email: 'alice@example.com' })
}
return err(`User ${id} not found`)
}
// Example of pattern matching
findUser(1).match({
ok: user => `Found user: ${user.name}`,
err: error => `Error: ${error}`,
})
// ============================================================================
// Example 4: Handling nullable values
// ============================================================================
interface Config {
apiKey?: string
timeout?: number
}
function getApiKey(config: Config): Result<string, string> {
return fromNullable(config.apiKey, 'API key is required')
}
const config: Config = { timeout: 5000 }
// Example of handling nullable values
getApiKey(config) // Result<string, string>
// ============================================================================
// Example 5: Converting exceptions to Results
// ============================================================================
function parseJSON<T>(json: string): Result<T, string> {
return tryCatch(
() => JSON.parse(json) as T,
(error) => {
if (error instanceof Error) {
return error.message
}
return 'Unknown error'
},
)
}
// Example of parsing JSON safely
parseJSON<{ name: string }>('{"name": "Alice"}')
// ============================================================================
// Example 6: Async operations
// ============================================================================
async function fetchUser(id: number): Promise<Result<User, string>> {
return tryCatchAsync(
async () => {
const response = await fetch(`https://api.example.com/users/${id}`)
if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}
return response.json() as Promise<User>
},
error => error instanceof Error ? error.message : 'Unknown error',
)
}
// ============================================================================
// Example 7: Combining multiple Results
// ============================================================================
interface UserProfile {
user: User
age: number
country: string
}
function getUser(): Result<User, string> {
return ok({ id: 1, name: 'Alice', email: 'alice@example.com' })
}
function getAge(): Result<number, string> {
return ok(30)
}
function getCountry(): Result<string, string> {
return ok('USA')
}
// Combine all results - stops at first error
// @ts-expect-error - Complex type inference with combine function
const profileResult = combine([getUser(), getAge(), getCountry()])
if (profileResult.isOk) {
const values = profileResult.value
const profile: UserProfile = {
user: values[0] as User,
age: values[1] as number,
country: values[2] as string,
}
// eslint-disable-next-line no-console
console.log(profile)
}
// ============================================================================
// Example 8: Form validation with combineWithAllErrors
// ============================================================================
interface FormData {
email: string
password: string
age: string
}
function validateEmail(email: string): Result<string, string> {
const emailRegex = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
return emailRegex.test(email) ? ok(email) : err('Invalid email format')
}
function validatePassword(password: string): Result<string, string> {
return password.length >= 8 ? ok(password) : err('Password must be at least 8 characters')
}
function validateAge(age: string): Result<number, string> {
const num = Number.parseInt(age)
if (Number.isNaN(num))
return err('Age must be a number')
if (num < 18)
return err('Must be 18 or older')
return ok(num)
}
function validateForm(data: FormData): Result<readonly unknown[], unknown[]> {
// Collect all errors instead of stopping at first one
return combineWithAllErrors(
// @ts-expect-error - Complex type inference with combineWithAllErrors
[validateEmail(data.email), validatePassword(data.password), validateAge(data.age)],
)
}
const formData: FormData = {
email: 'invalid-email',
password: 'short',
age: '15',
}
const validationResult = validateForm(formData)
if (validationResult.isErr) {
// eslint-disable-next-line no-console
console.log('Validation errors:', validationResult.error)
// Type: string[]
}
// ============================================================================
// Example 9: Railway-oriented programming
// ============================================================================
interface OrderData {
productId: string
quantity: number
userId: string
}
interface Product {
id: string
name: string
price: number
stock: number
}
interface Order {
id: string
product: Product
quantity: number
total: number
}
function validateQuantity(quantity: number): Result<number, string> {
return quantity > 0 ? ok(quantity) : err('Quantity must be positive')
}
function findProduct(productId: string): Result<Product, string> {
// Simulated product lookup
return ok({
id: productId,
name: 'Widget',
price: 9.99,
stock: 100,
})
}
function checkStock(product: Product, quantity: number): Result<Product, string> {
return product.stock >= quantity
? ok(product)
: err(`Insufficient stock. Available: ${product.stock}`)
}
function calculateTotal(product: Product, quantity: number): number {
return product.price * quantity
}
function createOrder(orderData: OrderData): Result<Order, string> {
return validateQuantity(orderData.quantity)
// eslint-disable-next-line no-unused-vars
.andThen(quantity =>
findProduct(orderData.productId)
.andThen(product => checkStock(product, quantity))
.map((product) => {
const order: Order = {
id: crypto.randomUUID(),
product,
quantity,
total: calculateTotal(product, quantity),
}
return order
}),
)
}
// ============================================================================
// Example 10: Working with arrays using traverse
// ============================================================================
function processNumbers(inputs: string[]): Result<number[], string> {
return traverse(inputs, (input) => {
const num = Number.parseFloat(input)
return Number.isNaN(num) ? err(`Invalid number: ${input}`) : ok(num)
})
}
// Examples of processing arrays with traverse
processNumbers(['1', '2', '3'])
// Result<number[], string> = Ok([1, 2, 3])
processNumbers(['1', 'invalid', '3'])
// Result<number[], string> = Err("Invalid number: invalid")
// ============================================================================
// Example 11: Error recovery with orElse
// ============================================================================
function fetchFromPrimaryCache(_key: string): Result<string, string> {
return err('Cache miss')
}
function fetchFromSecondaryCache(_key: string): Result<string, string> {
return err('Cache miss')
}
function fetchFromDatabase(_key: string): Result<string, string> {
return ok('data from database')
}
function getData(key: string): Result<string, string> {
return fetchFromPrimaryCache(key)
.orElse(() => fetchFromSecondaryCache(key))
.orElse(() => fetchFromDatabase(key))
}
// ============================================================================
// Example 12: Type-safe error transformation with mapErr
// ============================================================================
enum ErrorCode {
NotFound = 'NOT_FOUND',
Unauthorized = 'UNAUTHORIZED',
ValidationError = 'VALIDATION_ERROR',
}
interface ApiError {
code: ErrorCode
message: string
timestamp: Date
}
function validateInput(input: string): Result<string, string> {
return input.length > 0 ? ok(input) : err('Input cannot be empty')
}
function processWithApiError(input: string): Result<string, ApiError> {
return validateInput(input).mapErr((errorMessage) => {
const error: ApiError = {
code: ErrorCode.ValidationError,
message: errorMessage,
timestamp: new Date(),
}
return error
})
}
// ============================================================================
// Example 13: Practical API client example
// ============================================================================
class HttpError {
constructor(
public status: number,
public message: string,
) {}
}
async function makeRequest<T>(url: string) {
return tryCatchAsync(
async () => {
const response = await fetch(url)
if (!response.ok) {
throw new HttpError(response.status, response.statusText)
}
return response.json() as Promise<T>
},
(error) => {
if (error instanceof HttpError) {
return error
}
return new HttpError(500, 'Internal error')
},
)
}
// Usage with full type safety
// eslint-disable-next-line no-unused-vars
async function getUserProfile(userId: string): Promise<
{ success: true, user: User } | { success: false, error: string }
> {
const result = await makeRequest<User>(`/api/users/${userId}`)
if (result.isOk) {
return { success: true as const, user: result.value }
}
else {
return {
success: false as const,
error: `Failed to fetch user: ${result.error.message} (${result.error.status})`,
}
}
}
// ============================================================================
// Export examples for documentation
// ============================================================================
export {
createOrder,
divideBasic,
fetchUser,
getData,
getUserProfile,
parseJSON,
parseNumber,
processNumbers,
processWithApiError,
sqrt,
validateForm,
validatePositive,
}