#Checking Results
Before you can read the contents of a Result, you need to know whether it is a success or a failure.
This page covers the type guard functions that check a Result and narrow its type.
#Checking for Success with isSuccess
isSuccess returns true if the Result is a Success.
Inside the if block, TypeScript narrows the type so that you can safely access value:
import { import Result Result } from '@praha/byethrow';
const const result: Result.Result<number, string> result : import Result Result .type Result<T, E> = Result.Success<T> | Result.Failure<E>A union type representing either a success or a failure.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const doSomething = (): Result.Result<number, string> => {
return Math.random() > 0.5
? { type: 'Success', value: 10 }
: { type: 'Failure', error: 'Oops' };
};
@categoryCore Types Result <number, string> = import Result Result .function succeed<42>(value: 42): Result.Result<42, never> (+1 overload)Creates a
Success
result from a given value.
Passing a Promise is allowed, but it is recommended to await it before passing to succeed.
@typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith No Value
import { Result } from '@praha/byethrow';
const result = Result.succeed();
// Result.Result<void, never>
@seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators succeed (42);
if (import Result Result .function isSuccess<Result.Result<number, string>>(result: Result.Result<number, string>): result is Result.Success<number>Type guard to check if a
Result
is a
Success
.
@typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Success , otherwise false.@exampleimport { Result } from '@praha/byethrow';
const result: Result.Result<number, string> = { type: 'Success', value: 10 };
if (Result.isSuccess(result)) {
console.log(result.value); // Safe access to value
}
@categoryType Guards isSuccess (const result: Result.Result<number, string> result )) {
// result is narrowed to Success<number>
var console: Console console .Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
log (const result: Result.Success<number> result .value: number value ); // 42
}Narrowing also works for the other branch.
If the result is not a Success, it must be a Failure, so error is available there:
import { import Result Result } from '@praha/byethrow';
const const describe: (result: Result.Result<string, Error>) => string describe = (result: Result.Result<string, Error> result : import Result Result .type Result<T, E> = Result.Success<T> | Result.Failure<E>A union type representing either a success or a failure.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const doSomething = (): Result.Result<number, string> => {
return Math.random() > 0.5
? { type: 'Success', value: 10 }
: { type: 'Failure', error: 'Oops' };
};
@categoryCore Types Result <string, Error>) => {
if (import Result Result .function isSuccess<Result.Result<string, Error>>(result: Result.Result<string, Error>): result is Result.Success<string>Type guard to check if a
Result
is a
Success
.
@typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Success , otherwise false.@exampleimport { Result } from '@praha/byethrow';
const result: Result.Result<number, string> = { type: 'Success', value: 10 };
if (Result.isSuccess(result)) {
console.log(result.value); // Safe access to value
}
@categoryType Guards isSuccess (result: Result.Result<string, Error> result )) {
// ✅ `value` is available here
return result: Result.Success<string> result .value: string value .String.toUpperCase(): stringConverts all the alphabetic characters in a string to uppercase.
toUpperCase ();
}
// ✅ `error` is available here
return `Error: ${result: Result.Failure<Error> result .error: Error error .Error.message: string message }`;
};#Checking for Failure with isFailure
isFailure is the counterpart of isSuccess. It returns true if the Result is a Failure:
import { import Result Result } from '@praha/byethrow';
const const result: Result.Result<number, string> result : import Result Result .type Result<T, E> = Result.Success<T> | Result.Failure<E>A union type representing either a success or a failure.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const doSomething = (): Result.Result<number, string> => {
return Math.random() > 0.5
? { type: 'Success', value: 10 }
: { type: 'Failure', error: 'Oops' };
};
@categoryCore Types Result <number, string> = import Result Result .function fail<"Something went wrong">(error: "Something went wrong"): Result.Result<never, "Something went wrong"> (+1 overload)Creates a
Failure
result from a given error.
Passing a Promise is allowed, but it is recommended to await it before passing to fail.
@typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.fail('Something went wrong');
// Result.Result<never, string>
@exampleWith No Value
import { Result } from '@praha/byethrow';
const result = Result.fail();
// Result.Result<never, void>
@seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators fail ('Something went wrong');
if (import Result Result .function isFailure<Result.Result<number, string>>(result: Result.Result<number, string>): result is Result.Failure<string>Type guard to check if a
Result
is a
Failure
.
@typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Failure , otherwise false.@exampleimport { Result } from '@praha/byethrow';
const result: Result.Result<number, string> = { type: 'Failure', error: 'Something went wrong' };
if (Result.isFailure(result)) {
console.error(result.error); // Safe access to error
}
@categoryType Guards isFailure (const result: Result.Result<number, string> result )) {
// result is narrowed to Failure<string>
var console: Console console .Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
log (const result: Result.Failure<string> result .error: string error ); // "Something went wrong"
}#Early Return
A common pattern is to handle the failure first and return early.
After the if block, the result is known to be a Success:
import { import Result Result } from '@praha/byethrow';
const const getUserName: (result: Result.Result<User, string>) => string | null getUserName = (result: Result.Result<User, string> result : import Result Result .type Result<T, E> = Result.Success<T> | Result.Failure<E>A union type representing either a success or a failure.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const doSomething = (): Result.Result<number, string> => {
return Math.random() > 0.5
? { type: 'Success', value: 10 }
: { type: 'Failure', error: 'Oops' };
};
@categoryCore Types Result <type User = {
id: number;
name: string;
}
User , string>) => {
if (import Result Result .function isFailure<Result.Result<User, string>>(result: Result.Result<User, string>): result is Result.Failure<string>Type guard to check if a
Result
is a
Failure
.
@typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Failure , otherwise false.@exampleimport { Result } from '@praha/byethrow';
const result: Result.Result<number, string> = { type: 'Failure', error: 'Something went wrong' };
if (Result.isFailure(result)) {
console.error(result.error); // Safe access to error
}
@categoryType Guards isFailure (result: Result.Result<User, string> result )) {
var console: Console console .Console.error(...data: any[]): voidThe console.error() static method outputs a message to the console at the "error" log level. The message is only displayed to the user if the console is configured to display error output. In most cases, the log level is configured within the console UI. The message may be formatted as an error, with red colors and call stack information.
error ('Failed to find user:', result: Result.Failure<string> result .error: string error );
return null;
}
// result is narrowed to Success<User>
return result: Result.Success<User> result .value: User value .name: string name ;
};
Prefer Result.isFailure(result) over !Result.isSuccess(result), and vice versa.
The no-negated-type-guards lint rule enforces this automatically.
#Checking Whether a Value Is a Result with isResult
isResult checks whether an arbitrary value is a Result at all.
This is useful when you receive a value of an unknown type:
import { import Result Result } from '@praha/byethrow';
const const stringify: (value: unknown) => string stringify = (value: unknown value : unknown): string => {
if (import Result Result .function isResult<unknown, unknown>(result: unknown): result is Result.Result<unknown, unknown>Type guard to check if a value is a
Result
.
@typeParamT - The type of the success value.@typeParamE - The type of the error value.@paramresult - The value to check.@returnstrue if the value is a Result, otherwise false.@exampleimport { Result } from '@praha/byethrow';
const value: unknown = { type: 'Success', value: 42 };
if (Result.isResult(value)) {
// value is now typed as Result<unknown, unknown>
console.log(value.type); // 'Success' or 'Failure'
}
@categoryType Guards isResult (value: unknown value )) {
// value is narrowed to Result<unknown, unknown>
if (import Result Result .function isSuccess<Result.Result<unknown, unknown>>(result: Result.Result<unknown, unknown>): result is Result.Success<unknown>Type guard to check if a
Result
is a
Success
.
@typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Success , otherwise false.@exampleimport { Result } from '@praha/byethrow';
const result: Result.Result<number, string> = { type: 'Success', value: 10 };
if (Result.isSuccess(result)) {
console.log(result.value); // Safe access to value
}
@categoryType Guards isSuccess (value: Result.Result<unknown, unknown> value )) {
return `Success: ${var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON .JSON.stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string (+1 overload)Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
@paramvalue A JavaScript value, usually an object or array, to be converted.@paramreplacer A function that transforms the results.@paramspace Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.@throws{TypeError} If a circular reference or a BigInt value is found. stringify (value: Result.Success<unknown> value .value: unknown value )}`;
}
return `Failure: ${var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON .JSON.stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string (+1 overload)Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
@paramvalue A JavaScript value, usually an object or array, to be converted.@paramreplacer A function that transforms the results.@paramspace Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.@throws{TypeError} If a circular reference or a BigInt value is found. stringify (value: Result.Failure<unknown> value .error: unknown error )}`;
}
return var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON .JSON.stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string (+1 overload)Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
@paramvalue A JavaScript value, usually an object or array, to be converted.@paramreplacer A function that transforms the results.@paramspace Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.@throws{TypeError} If a circular reference or a BigInt value is found. stringify (value: unknown value );
};#References
| API | Purpose |
|---|---|
| isSuccess(result) | Check whether a Result is a Success |
| isFailure(result) | Check whether a Result is a Failure |
| isResult(value) | Check whether a value is a Result |
