@rtorcato/js-common / try
try
Type Aliases
Success
Success<
T> =object
Defined in: try/index.ts:4
Successful branch of a Result — carries the value and a null error.
Type Parameters
T
T
Properties
data
data:
T
Defined in: try/index.ts:4
error
error:
null
Defined in: try/index.ts:4
Failure
Failure<
E> =object
Defined in: try/index.ts:9
Error branch of a Result — carries a null value and an error of type E.
Type Parameters
E
E
Properties
data
data:
null
Defined in: try/index.ts:9
error
error:
E
Defined in: try/index.ts:9
Result
Defined in: try/index.ts:21
Go-style discriminated union representing either a Success<T> or a Failure<E>,
for async code that prefers explicit error returns over thrown exceptions.
Example
const ok: Result<number> = { data: 42, error: null }
const bad: Result<number> = { data: null, error: new Error('boom') }
Functions
Type Parameters
T
T
E
E = Error
isSuccess()
isSuccess<
T,E>(result):result is Success<T>
Defined in: try/index.ts:34
Type guard that narrows a Result to its Success branch when the error is null.
Example
const result = await tryCatch(async () => 42)
if (isSuccess(result)) {
result.data // 42, narrowed to number
}
Type Parameters
T
T
E
E
Parameters
result
Result<T, E>
Returns
result is Success<T>
tryCatch()
tryCatch<
T,E>(fn):Promise<Result<T,E>>
Defined in: try/index.ts:52
Run an async function and capture any thrown error into a Result, eliminating
try/catch at the call site.
Example
const { data, error } = await tryCatch(() => fetch('/api/user').then((r) => r.json()))
// success: { data: { id: 1 }, error: null }
// failure: { data: null, error: Error }
if (error) return console.error(error)
console.log(data.id)
Type Parameters
T
T
E
E = Error
Parameters
fn
() => Promise<T>
Returns
Promise<Result<T, E>>