61 lines
2.5 KiB
Markdown
61 lines
2.5 KiB
Markdown
---
|
|
name: native-monad-option
|
|
description: "Option<T> API reference. ALWAYS invoke when using Some, None, Option, OptionPromise, Option.from, Option.all, Option.partition, option.map, option.flatMap, option.match(2 args), option.filter(NO errorFactory). Do not guess Option methods — consult this skill."
|
|
---
|
|
|
|
# Option<T> Usage Guide
|
|
|
|
## Quick Reference
|
|
|
|
| Method | Signature (on Some) | Signature (on None) |
|
|
|-------------------------|--------------------------------|---------------------|
|
|
| `isSome()` | `this is Some<T>` | `this is never` |
|
|
| `isNone()` | `this is never` | `this is None` |
|
|
| `map(fn)` | `(fn: (v: T) => U) => Some<U>` | `() => None` |
|
|
| `flatMap(fn)` | `(fn: (v: T) => R) => R` | `() => this` |
|
|
| `match(onSome, onNone)` | 2 callbacks | 2 callbacks |
|
|
| `filter(pred)` | NO errorFactory | `() => None` |
|
|
| `toNullable()` | `T` | `null` |
|
|
| `toUndefined()` | `T` | `undefined` |
|
|
| `toString()` | `string` | `string` |
|
|
|
|
## Critical Rules
|
|
|
|
1. `match()` takes exactly **2 callbacks**: `(onSome, onNone)`.
|
|
2. `filter()` takes ONLY a predicate — NO `errorFactory` (unlike Result).
|
|
3. Option has **NO** `mapErr()` or `flatMapErr()` — those are Result/Query only.
|
|
4. `flatMap` constraint: `R extends Option<any>` — callback must return an Option.
|
|
5. Type guard: after `isSome()`, access `.value`. None has no `.value`.
|
|
6. `none()` returns a frozen singleton — do not try to construct `new None()`.
|
|
7. `Option.from()` treats only `null | undefined` as None. `0`, `false`, `""` become `Some`.
|
|
|
|
## Anti-Patterns
|
|
|
|
```typescript
|
|
// WRONG — Option.filter does NOT take errorFactory
|
|
option.filter((v) => v > 0, () => new Error("bad"));
|
|
|
|
// CORRECT — just a predicate
|
|
option.filter((v) => v > 0);
|
|
```
|
|
|
|
```typescript
|
|
// WRONG — mapErr does not exist on Option
|
|
option.mapErr((e) => new Error(e));
|
|
|
|
// CORRECT — Option has no error channel. Use Result if you need errors.
|
|
```
|
|
|
|
```typescript
|
|
// WRONG — fromNullable does not exist
|
|
Option.fromNullable(value);
|
|
|
|
// CORRECT
|
|
Option.from(value);
|
|
```
|
|
|
|
## Namespace & Async Methods
|
|
|
|
Read `references/api-surface.md` for the complete Option namespace (`.from`, `.all`, `.partition`, `.compact`, `.some`,
|
|
`.every`) and OptionPromise namespace.
|