I am working on functional programming using fp-ts library.
Here is my code and my problem:
import * as TE from 'fp-ts/TaskEither';
import { pipe } from 'fp-ts/lib/function';
function getName(): TE.TaskEither<Error, String> {
return TE.right('John Doe');
}
function getAge(): TE.TaskEither<Error, number> {
return TE.right(40);
}
export function seqArrayTest(): TE.TaskEither<Error, string> {
return pipe(
TE.sequenceArray([
getName(),
getAge(),
]),
TE.chain(([name, age]) => {
return TE.right(`Name: ${name}, Age: ${age}`);
}),
);
}
Here:
- I have two functions:
getNameandgetAgereturningTaskEitherwith different value types. - I am calling them parallel using
TE.sequenceArray. - After the computation, I am just chaining the response and returning another
TaskEither.
During compilation, on TE.sequenceArray([getName(), getAge()]), it shows below error for getAge():
Type 'TaskEither<Error, number>' is not assignable to type 'TaskEither<Error, String>'. Type 'number' is not assignable to type 'String'.ts(2322)
But my understanding is: TE.sequenceArray should take an array of functions with different return types that are wrapped with TaskEither and it will return an array of responses sequentially.
@Souperman answer is correct in this context.
TE.sequenceArrayexpects an array ofTaskEitherswith the sameRighttypes.If we want to process an array of
TaskEitherand the return type is different, then we may usesequenceT.Here is the modified code:
Here,
TE.ApplyPar: Runs computations in parallel. If we want sequential, then we may useTE.ApplySeq.In
TE.chain(([name, age])parameternameis astringtype, andageis anumbertype. And response sequence will based on the calling sequence.