Variable: fromNullable()
readonlyfromNullable: {<T>(value):Result<NonNullable<T>,Error>; <T,E>(value,onError):Result<NonNullable<T>,E>; }
Defined in: core/factories.ts:274
Call Signature
<
T>(value):Result<NonNullable<T>,Error>
Creates a Result from a value that may be null or undefined.
Useful for working with APIs that return nullable values and you want to force explicit handling of the null/undefined case.
Type Parameters
T
T
Value type
Parameters
value
Possibly null/undefined value
T | null | undefined
Returns
Result<NonNullable<T>, Error>
Ok if defined, Err with default error if null/undefined
Examples
// With present value
const value = Result.fromNullable(42)
// Ok(42)// With null
const empty = Result.fromNullable(null)
// Err(Error: Value is null or undefined)// Practical usage with find
const users = [{ id: 1, name: 'Ana' }, { id: 2, name: 'Bob' }]
const user = Result.fromNullable(
users.find((u) => u.id === 3)
)
// Err(Error: Value is null or undefined)Call Signature
<
T,E>(value,onError):Result<NonNullable<T>,E>
Creates a Result from nullable value with custom error.
Type Parameters
T
T
Value type
E
E
Error type
Parameters
value
Possibly null/undefined value
T | null | undefined
onError
() => E
Function that generates custom error
Returns
Result<NonNullable<T>, E>
Ok if defined, Err with custom error if null/undefined
Examples
// With personalized error
const config = Result.fromNullable(
process.env.API_KEY,
() => new Error('API_KEY not configured')
)// With custom error type
type NotFoundError = { code: 'NOT_FOUND'; resource: string }
const user = Result.fromNullable(
userMap.get(userId),
(): NotFoundError => ({ code: 'NOT_FOUND', resource: 'user' })
)