#Result を確認する
Result の中身を読み取る前に、それが成功なのか失敗なのかを知る必要があります。
このページでは、Result の状態を確認して型を絞り込む型ガード関数を紹介します。
#isSuccess で成功を確認する
isSuccess は、Result が Success の場合に true を返します。
if ブロックの中では TypeScript が型を絞り込むため、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 は 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
}型の絞り込みはもう一方の分岐でも働きます。
Success でなければ Failure のはずなので、そこでは error が使えます。
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` が使える
return result: Result.Success<string> result .value: string value .String.toUpperCase(): stringConverts all the alphabetic characters in a string to uppercase.
toUpperCase ();
}
// ✅ ここでは `error` が使える
return `Error: ${result: Result.Failure<Error> result .error: Error error .Error.message: string message }`;
};#isFailure で失敗を確認する
isFailure は isSuccess の対になる関数で、Result が Failure の場合に true を返します。
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 は 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"
}#早期リターン
よく使われるパターンは、先に失敗を処理して早期リターンすることです。
if ブロックの後では、結果が 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 は Success<User> に絞り込まれる
return result: Result.Success<User> result .value: User value .name: string name ;
};
!Result.isSuccess(result) よりも Result.isFailure(result) を使いましょう(逆も同様です)。
no-negated-type-guards Lint ルールを使うと、これを自動的に強制できます。
#isResult で値が Result かどうかを確認する
isResult は、任意の値がそもそも Result かどうかを確認します。
型のわからない値を受け取るときに便利です。
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 は 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 );
};#リファレンス
| API | 用途 |
|---|---|
| isSuccess(result) | Result が Success かどうかを確認する |
| isFailure(result) | Result が Failure かどうかを確認する |
| isResult(value) | 値が Result かどうかを確認する |
