55 lines
2.7 KiB
Markdown
55 lines
2.7 KiB
Markdown
---
|
|
name: native-monad-result
|
|
description: "Result<T,E> API reference. ALWAYS invoke when using Ok, Err, Result, ResultPromise, Result.from, Result.all, Result.partition, result.map, result.flatMap, result.match(2 args), result.filter(needs errorFactory). Do not guess Result methods — consult this skill."
|
|
---
|
|
|
|
# Result<T, E> Usage Guide
|
|
|
|
## Quick Reference
|
|
|
|
| Method | Signature (on Ok) | Signature (on Err) |
|
|
|------------------------------|------------------------------|-------------------------------|
|
|
| `isOk()` | `this is Ok<T>` | `this is never` |
|
|
| `isErr()` | `this is never` | `this is Err<E>` |
|
|
| `map(fn)` | `(fn: (v: T) => U) => Ok<U>` | `() => Err<E>` |
|
|
| `mapErr(fn)` | `(fn: (e: E) => F) => Ok<T>` | `(fn: (e: E) => F) => Err<F>` |
|
|
| `flatMap(fn)` | `(fn: (v: T) => R) => R` | `() => this` |
|
|
| `flatMapErr(fn)` | `() => this` | `(fn: (e: E) => R) => R` |
|
|
| `match(onOk, onErr)` | 2 callbacks | 2 callbacks |
|
|
| `filter(pred, errorFactory)` | requires `errorFactory` | `() => Err<E>` |
|
|
| `toNullable()` | `T` | `null` |
|
|
| `toUndefined()` | `T` | `undefined` |
|
|
| `toString()` | `string` | `string` |
|
|
|
|
## Critical Rules
|
|
|
|
1. `match()` takes exactly **2 callbacks**: `(onOk, onErr)`.
|
|
2. `filter()` REQUIRES an `errorFactory` parameter — it produces `Err<F>` when the predicate fails.
|
|
3. `flatMap` constraint: `R extends Result<any, any>` — the callback must return a Result.
|
|
4. `flatMapErr` constraint: `R extends Result<any, any>` — the callback must return a Result.
|
|
5. Type guard: after `isOk()`, access `.value`. After `isErr()`, access `.err`.
|
|
6. `Ok` stores `.value`. `Err` stores `.err` (not `.error`, not `.value`).
|
|
|
|
## Anti-Patterns
|
|
|
|
```typescript
|
|
// WRONG — filter without errorFactory
|
|
result.filter((v) => v > 0);
|
|
|
|
// CORRECT — filter always needs errorFactory
|
|
result.filter((v) => v > 0, (v) => new Error(`Invalid: ${v}`));
|
|
```
|
|
|
|
```typescript
|
|
// WRONG — match with 3 callbacks (that's Query, not Result)
|
|
result.match(onOk, onNone, onErr);
|
|
|
|
// CORRECT — Result.match takes exactly 2
|
|
result.match(onOk, onErr);
|
|
```
|
|
|
|
## Namespace & Async Methods
|
|
|
|
Read `references/api-surface.md` for the complete Result namespace (`.from`, `.all`, `.partition`, `.compact`, `.some`,
|
|
`.every`) and ResultPromise namespace.
|