Overview
Unwraps theOk value, or returns the provided default value if the Result is an Err. This is a safe way to extract values from a Result without throwing exceptions.
Signature
Parameters
A
required
The default value to return if the Result is an Err. This can be a different type than T.
Returns
ReturnsT | A where:
- If the Result is
Ok(value), returnsvalue(type T) - If the Result is
Err(error), returnsv(type A)
Examples
Basic Usage
With Transformations
Chaining Operations
Different Default Types
With Configuration
Form Input Parsing
API Response Handling
Safe Array Access
Equivalent to match
Real-World Database Query
Implementation Details
From the source code (result.ts:388-390):Err (result.ts:488-490):
Notes
- The default value is only used if the Result is an Err
- The default value is returned as-is, it’s not wrapped in a Result
- Unlike
._unsafeUnwrap(), this never throws an exception - Can be combined with
.map()to transform before unwrapping - The default value can be a different type than the Ok value
- More restrictive than match() since you can’t access the error value
Use Cases
- Providing fallback values for failed operations
- Setting defaults for configuration loading
- Ensuring non-null values in UI rendering
- Safe parsing with sensible defaults
- Converting Results to plain values for compatibility
Related
- Result.match() - Handle both Ok and Err with full control
- Result.map() - Transform before unwrapping
- Result.orElse() - Recover with another Result