Skip to main content

Function: tryCatch()

tryCatch<T>(fn): Option<T>

Defined in: option/constructors/index.ts:101

Wraps a potentially throwing function in an Option.

If the function executes successfully, returns Some with the value. If it throws, returns None.

Type Parameters

T

T

Parameters

fn

() => T

Function that may throw

Returns

Option<T>

Option containing either the return value or None

Example

const parseJSON = (str: string) =>
tryCatch(() => JSON.parse(str))

parseJSON('{"name":"John"}')
// => Some({ name: 'John' })

parseJSON('invalid json')
// => None