#Result を変換する
map と mapError は、Result が Success か Failure かを変えずに、その中身を変換します。
#map で値を変換する
map(fn)ケースを選ぶと、その流れだけを追えますmap は、渡された関数で成功値を変換します。
Result が Failure の場合、関数は呼び出されず、Failure がそのまま返されます。
import { import Result Result } from '@praha/byethrow';
const const success: Result.Result<number, never> success = import Result Result .function pipe<Result.Result<2, never>, Result.Result<number, never>>(a: Result.Result<2, never>, ab: (a: Result.Result<2, never>) => Result.Result<number, never>): Result.Result<number, never> (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Result Result .function succeed<2>(value: 2): Result.Result<2, 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 (2),
import Result Result .function map<Result.Result<2, never>, number>(fn: (a: 2) => number): (result: Result.Result<2, never>) => Result.Result<number, never> (+1 overload)Applies a transformation function to the success value of a
Result
or
ResultAsync
.
If the input is a
Failure
, it will be returned unchanged.
@typeParamR1 - The input Result or ResultAsync .@typeParamT2 - The transformed success value type.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(2),
Result.map((x) => x * 10),
);
// { type: 'Success', value: 20 }
@exampleFailure Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.map((x) => x * 10),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators map ((value: 2 value ) => value: 2 value * 10),
);
// { type: 'Success', value: 20 }
const const failure: Result.Result<number, "error"> failure = import Result Result .function pipe<Result.Result<never, "error">, Result.Result<number, "error">>(a: Result.Result<never, "error">, ab: (a: Result.Result<never, "error">) => Result.Result<number, "error">): Result.Result<number, "error"> (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Result Result .function fail<"error">(error: "error"): Result.Result<never, "error"> (+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 ('error'),
import Result Result .function map<Result.Result<never, "error">, number>(fn: (a: never) => number): (result: Result.Result<never, "error">) => Result.Result<number, "error"> (+1 overload)Applies a transformation function to the success value of a
Result
or
ResultAsync
.
If the input is a
Failure
, it will be returned unchanged.
@typeParamR1 - The input Result or ResultAsync .@typeParamT2 - The transformed success value type.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(2),
Result.map((x) => x * 10),
);
// { type: 'Success', value: 20 }
@exampleFailure Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.map((x) => x * 10),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators map ((value: never value ) => value: never value * 10), // 呼び出されない
);
// { type: 'Failure', error: 'error' }#例:表示用にデータを整形する
map のよくある使い方は、生のデータを UI が必要とする形に変換することです。
import { import Result Result } from '@praha/byethrow';
type type ProductRow = {
id: number;
name: string;
priceInCents: number;
}
ProductRow = {
id: number id : number;
name: string name : string;
priceInCents: number priceInCents : number;
};
type type ProductView = {
id: string;
name: string;
price: string;
}
ProductView = {
id: string id : string;
name: string name : string;
price: string price : string;
};
const const toProductView: (product: ProductRow) => ProductView toProductView = (product: ProductRow product : type ProductRow = {
id: number;
name: string;
priceInCents: number;
}
ProductRow ): type ProductView = {
id: string;
name: string;
price: string;
}
ProductView => ({
id: string id : var String: StringConstructor
(value?: any) => string
Allows manipulation and formatting of text strings and determination and location of substrings within strings.
String (product: ProductRow product .id: number id ),
name: string name : product: ProductRow product .name: string name ,
price: string price : `$${(product: ProductRow product .priceInCents: number priceInCents / 100).Number.toFixed(fractionDigits?: number): stringReturns a string representing a number in fixed-point notation.
@paramfractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. toFixed (2)}`,
});
const const getProductForDisplay: (id: number) => Result.ResultAsync<ProductView, "NotFound"> getProductForDisplay = (id: number id : number): import Result Result .type ResultAsync<T, E> = Promise<Result.Result<T, E>>An asynchronous variant of
Result
, wrapped in a Promise.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const fetchData = async (): Result.ResultAsync<string, Error> => {
try {
const data = await fetch('...');
return { type: 'Success', value: await data.text() };
} catch (err) {
return { type: 'Failure', error: err as Error };
}
};
@categoryCore Types ResultAsync <type ProductView = {
id: string;
name: string;
price: string;
}
ProductView , 'NotFound'> => {
return import Result Result .function pipe<Result.ResultAsync<ProductRow, "NotFound">, Result.ResultAsync<ProductView, "NotFound">>(a: Result.ResultAsync<ProductRow, "NotFound">, ab: (a: Result.ResultAsync<ProductRow, "NotFound">) => Result.ResultAsync<ProductView, "NotFound">): Result.ResultAsync<ProductView, "NotFound"> (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
const fetchProduct: (id: number) => Result.ResultAsync<ProductRow, "NotFound"> fetchProduct (id: number id ),
import Result Result .function map<Result.ResultAsync<ProductRow, "NotFound">, ProductView>(fn: (a: ProductRow) => ProductView): (result: Result.ResultAsync<ProductRow, "NotFound">) => Result.ResultAsync<ProductView, "NotFound"> (+1 overload)Applies a transformation function to the success value of a
Result
or
ResultAsync
.
If the input is a
Failure
, it will be returned unchanged.
@typeParamR1 - The input Result or ResultAsync .@typeParamT2 - The transformed success value type.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(2),
Result.map((x) => x * 10),
);
// { type: 'Success', value: 20 }
@exampleFailure Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.map((x) => x * 10),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators map (const toProductView: (product: ProductRow) => ProductView toProductView ),
);
};#mapError でエラーを変換する
mapError(fn)ケースを選ぶと、その流れだけを追えますmapError は、エラーに対する map の対になる関数です。
エラー値を変換し、Success の場合は関数を呼び出さずにそのまま返します。
import { import Result Result } from '@praha/byethrow';
const const failure: Result.Result<never, Error> failure = import Result Result .function pipe<Result.Result<never, "NotFound">, Result.Result<never, Error>>(a: Result.Result<never, "NotFound">, ab: (a: Result.Result<never, "NotFound">) => Result.Result<never, Error>): Result.Result<never, Error> (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Result Result .function fail<"NotFound">(error: "NotFound"): Result.Result<never, "NotFound"> (+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 ('NotFound'),
import Result Result .function mapError<Result.Result<never, "NotFound">, Error>(fn: (a: "NotFound") => Error): (result: Result.Result<never, "NotFound">) => Result.Result<never, Error> (+1 overload)Applies a transformation function to the error value of a
Result
or
ResultAsync
.
If the input is a
Success
, it will be returned unchanged.
@typeParamR1 - The input Result or ResultAsync .@typeParamE2 - The transformed error value type.@exampleFailure Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('NotFound'),
Result.mapError((error) => new Error(error)),
);
// { type: 'Failure', error: Error('NotFound') }
@exampleSuccess Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(123),
Result.mapError((error) => new Error(error)),
);
// { type: 'Success', value: 123 }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators mapError ((error: "NotFound" error ) => new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error (error: "NotFound" error )),
);
// { type: 'Failure', error: Error('NotFound') }
const const success: Result.Result<123, Error> success = import Result Result .function pipe<Result.Result<123, never>, Result.Result<123, Error>>(a: Result.Result<123, never>, ab: (a: Result.Result<123, never>) => Result.Result<123, Error>): Result.Result<123, Error> (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Result Result .function succeed<123>(value: 123): Result.Result<123, 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 (123),
import Result Result .function mapError<Result.Result<123, never>, Error>(fn: (a: never) => Error): (result: Result.Result<123, never>) => Result.Result<123, Error> (+1 overload)Applies a transformation function to the error value of a
Result
or
ResultAsync
.
If the input is a
Success
, it will be returned unchanged.
@typeParamR1 - The input Result or ResultAsync .@typeParamE2 - The transformed error value type.@exampleFailure Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('NotFound'),
Result.mapError((error) => new Error(error)),
);
// { type: 'Failure', error: Error('NotFound') }
@exampleSuccess Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(123),
Result.mapError((error) => new Error(error)),
);
// { type: 'Success', value: 123 }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators mapError ((error: never error ) => new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error (error: never error )), // 呼び出されない
);
// { type: 'Success', value: 123 }#例:ドメインエラーを HTTP エラーに変換する
mapError のよくある使い方は、ある層のエラーを別の層の言葉に翻訳することです。たとえば、ドメインエラーを HTTP レスポンスに変換します。
import { import Result Result } from '@praha/byethrow';
type type DomainError = {
type: "NotFound";
resource: string;
} | {
type: "ValidationError";
field: string;
message: string;
} | {
type: "Unauthorized";
}
DomainError =
| { type: "NotFound" type : 'NotFound'; resource: string resource : string }
| { type: "ValidationError" type : 'ValidationError'; field: string field : string; message: string message : string }
| { type: "Unauthorized" type : 'Unauthorized' };
type type HttpError = {
status: number;
body: {
error: string;
details?: string;
};
}
HttpError = {
status: number status : number;
body: {
error: string;
details?: string;
}
body : { error: string error : string; details?: string | undefined details ?: string };
};
const const toHttpError: (error: DomainError) => HttpError toHttpError = (error: DomainError error : type DomainError = {
type: "NotFound";
resource: string;
} | {
type: "ValidationError";
field: string;
message: string;
} | {
type: "Unauthorized";
}
DomainError ): type HttpError = {
status: number;
body: {
error: string;
details?: string;
};
}
HttpError => {
switch (error: DomainError error .type: "NotFound" | "ValidationError" | "Unauthorized" type ) {
case 'NotFound':
return {
status: number status : 404,
body: {
error: string;
details?: string;
}
body : { error: string error : 'Not Found', details?: string | undefined details : `${error: {
type: "NotFound";
resource: string;
}
error .resource: string resource } was not found` },
};
case 'ValidationError':
return {
status: number status : 400,
body: {
error: string;
details?: string;
}
body : { error: string error : 'Bad Request', details?: string | undefined details : `${error: {
type: "ValidationError";
field: string;
message: string;
}
error .field: string field }: ${error: {
type: "ValidationError";
field: string;
message: string;
}
error .message: string message }` },
};
case 'Unauthorized':
return {
status: number status : 401,
body: {
error: string;
details?: string;
}
body : { error: string error : 'Unauthorized' },
};
}
};
const const handleRequest: () => Result.ResultAsync<{
data: string;
}, HttpError>
handleRequest = (): import Result Result .type ResultAsync<T, E> = Promise<Result.Result<T, E>>An asynchronous variant of
Result
, wrapped in a Promise.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const fetchData = async (): Result.ResultAsync<string, Error> => {
try {
const data = await fetch('...');
return { type: 'Success', value: await data.text() };
} catch (err) {
return { type: 'Failure', error: err as Error };
}
};
@categoryCore Types ResultAsync <{ data: string data : string }, type HttpError = {
status: number;
body: {
error: string;
details?: string;
};
}
HttpError > => {
return import Result Result .function pipe<Result.ResultAsync<{
data: string;
}, DomainError>, Result.ResultAsync<{
data: string;
}, HttpError>>(a: Result.ResultAsync<{
data: string;
}, DomainError>, ab: (a: Result.ResultAsync<{
data: string;
}, DomainError>) => Result.ResultAsync<{
data: string;
}, HttpError>): Result.ResultAsync<{
data: string;
}, HttpError> (+25 overloads)
Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
const processRequest: () => Result.ResultAsync<{
data: string;
}, DomainError>
processRequest (),
import Result Result .function mapError<Result.ResultAsync<{
data: string;
}, DomainError>, HttpError>(fn: (a: DomainError) => HttpError): (result: Result.ResultAsync<{
data: string;
}, DomainError>) => Result.ResultAsync<{
data: string;
}, HttpError> (+1 overload)
Applies a transformation function to the error value of a
Result
or
ResultAsync
.
If the input is a
Success
, it will be returned unchanged.
@typeParamR1 - The input Result or ResultAsync .@typeParamE2 - The transformed error value type.@exampleFailure Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('NotFound'),
Result.mapError((error) => new Error(error)),
);
// { type: 'Failure', error: Error('NotFound') }
@exampleSuccess Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(123),
Result.mapError((error) => new Error(error)),
);
// { type: 'Success', value: 123 }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators mapError (const toHttpError: (error: DomainError) => HttpError toHttpError ),
);
};#map と mapError を組み合わせる
2 つの関数は同じパイプラインの中で併用できます。 結果が成功か失敗かに応じて、実際に実行されるのはどちらか一方だけです。
import { import Result Result } from '@praha/byethrow';
const const getUserForView: (id: number) => Result.ResultAsync<UserView, HttpError> getUserForView = (id: number id : number): import Result Result .type ResultAsync<T, E> = Promise<Result.Result<T, E>>An asynchronous variant of
Result
, wrapped in a Promise.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const fetchData = async (): Result.ResultAsync<string, Error> => {
try {
const data = await fetch('...');
return { type: 'Success', value: await data.text() };
} catch (err) {
return { type: 'Failure', error: err as Error };
}
};
@categoryCore Types ResultAsync <type UserView = {
id: string;
fullName: string;
}
UserView , type HttpError = {
status: number;
body: {
error: string;
};
}
HttpError > => {
return import Result Result .function pipe<Result.ResultAsync<UserRow, DatabaseError>, Result.ResultAsync<UserView, DatabaseError>, Result.ResultAsync<UserView, HttpError>>(a: Result.ResultAsync<UserRow, DatabaseError>, ab: (a: Result.ResultAsync<UserRow, DatabaseError>) => Result.ResultAsync<UserView, DatabaseError>, bc: (b: Result.ResultAsync<UserView, DatabaseError>) => Result.ResultAsync<...>): Result.ResultAsync<...> (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
const fetchUser: (id: number) => Result.ResultAsync<UserRow, DatabaseError> fetchUser (id: number id ),
import Result Result .function map<Result.ResultAsync<UserRow, DatabaseError>, UserView>(fn: (a: UserRow) => UserView): (result: Result.ResultAsync<UserRow, DatabaseError>) => Result.ResultAsync<UserView, DatabaseError> (+1 overload)Applies a transformation function to the success value of a
Result
or
ResultAsync
.
If the input is a
Failure
, it will be returned unchanged.
@typeParamR1 - The input Result or ResultAsync .@typeParamT2 - The transformed success value type.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(2),
Result.map((x) => x * 10),
);
// { type: 'Success', value: 20 }
@exampleFailure Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.map((x) => x * 10),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators map (const toView: (row: UserRow) => UserView toView ), // 成功時のみ実行される
import Result Result .function mapError<Result.ResultAsync<UserView, DatabaseError>, HttpError>(fn: (a: DatabaseError) => HttpError): (result: Result.ResultAsync<UserView, DatabaseError>) => Result.ResultAsync<UserView, HttpError> (+1 overload)Applies a transformation function to the error value of a
Result
or
ResultAsync
.
If the input is a
Success
, it will be returned unchanged.
@typeParamR1 - The input Result or ResultAsync .@typeParamE2 - The transformed error value type.@exampleFailure Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('NotFound'),
Result.mapError((error) => new Error(error)),
);
// { type: 'Failure', error: Error('NotFound') }
@exampleSuccess Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(123),
Result.mapError((error) => new Error(error)),
);
// { type: 'Success', value: 123 }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators mapError (const toHttpError: (error: DatabaseError) => HttpError toHttpError ), // 失敗時のみ実行される
);
};#map か andThen か?
map に渡す関数は、プレーンな値を返す必要があります。
変換そのものが失敗しうるために関数が Result を返す場合は、代わりに andThen を使ってください。andThen は次のページで解説します。
import { import Result Result } from '@praha/byethrow';
// ❌ map は返された Result をさらに Result で包んでしまう
const const nested: Result.Result<Result.Result<number, string>, never> nested = import Result Result .function pipe<Result.Result<"20", never>, Result.Result<Result.Result<number, string>, never>>(a: Result.Result<"20", never>, ab: (a: Result.Result<"20", never>) => Result.Result<Result.Result<number, string>, never>): Result.Result<Result.Result<number, string>, never> (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Result Result .function succeed<"20">(value: "20"): Result.Result<"20", 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 ('20'),
import Result Result .function map<Result.Result<"20", never>, Result.Result<number, string>>(fn: (a: "20") => Result.Result<number, string>): (result: Result.Result<"20", never>) => Result.Result<Result.Result<number, string>, never> (+1 overload)Applies a transformation function to the success value of a
Result
or
ResultAsync
.
If the input is a
Failure
, it will be returned unchanged.
@typeParamR1 - The input Result or ResultAsync .@typeParamT2 - The transformed success value type.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(2),
Result.map((x) => x * 10),
);
// { type: 'Success', value: 20 }
@exampleFailure Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.map((x) => x * 10),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators map (const parseAge: (input: string) => Result.Result<number, string> parseAge ),
);
// 型: Result.Result<Result.Result<number, string>, never>
// ✅ andThen は返された Result をそのまま次の結果として使う
const const flat: Result.Result<number, string> flat = import Result Result .function pipe<Result.Result<"20", never>, Result.Result<number, string>>(a: Result.Result<"20", never>, ab: (a: Result.Result<"20", never>) => Result.Result<number, string>): Result.Result<number, string> (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Result Result .function succeed<"20">(value: "20"): Result.Result<"20", 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 ('20'),
import Result Result .function andThen<Result.Result<"20", never>, Result.Result<number, string>>(fn: (a: "20") => Result.Result<number, string>): (result: Result.Result<"20", never>) => Result.Result<number, string> (+1 overload)Chains the next computation using the success value of a
Result
or
ResultAsync
.
If the original result is a
Failure
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.succeed(x * 2)),
);
// { type: 'Success', value: 6 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThen((x) => Result.succeed(x * 2)),
);
// result: { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.fail('error: ' + x)),
);
// result: { type: 'Failure', error: 'error: 3' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen (const parseAge: (input: string) => Result.Result<number, string> parseAge ),
);
// 型: Result.Result<number, string>#リファレンス
| API | 用途 |
|---|---|
| map(fn) | 成功値を変換する |
| mapError(fn) | エラー値を変換する |
