mohsen saremi
mohsen saremi

Reputation: 715

fp-ts pipeline with Option and chain not working

I have this sample code:

import {none, some, chain} from 'fp-ts/lib/Option';
import {pipe} from 'fp-ts/lib/pipeable';

const f1 = (input: string) => {
    return some(input + " f1")
};
const f2 = (input: string) => {
    return some(input + "f2")
};
const f3 = (input: string) => {
    return none;
};
const f4 = (input: string) => {
    return some(input + "f4");
};

const result = pipe(
    f1,
    chain(f2),
    chain(f3),
    chain(f4),
)("X");

console.log("result", result);

And I am getting this compile time error

Argument of type '(input: string) => Option<string>' is not assignable to parameter of type 'Option<string>'.
  Type '(input: string) => Option<string>' is missing the following properties from type 'Some<string>': _tag, value

18     f1,
       ~~

  src/index.ts:18:5
    18     f1,
           ~~
    Did you mean to call this expression?

What is wrong with my code?

I expect f1 and f2 to run and other function not because of none returning in f3 and at the end the output to be Some "X f1 f2"

Upvotes: 0

Views: 1836

Answers (1)

ford04
ford04

Reputation: 74510

The fp-ts pipe function expects the initial value "X" as first argument to facilitate TypeScript left to right generic inference.

So in contrast to other fp-libraries, where the initial value is passed in a curried manner, you create the pipe as follows:

const result = pipe(
  "X", // here is initial argument
  f1,
  chain(f2),
  chain(f3),
  chain(f4)
); // type: Option<string>, actual value is None

The return value will be None - once an option isNone, it will stay None, when you chain over it (implementation here):

chain((n: number) => some(n*2))(none) // stays None

Edit:

flow (equivalent of other libraries' pipe) is an alternative, that behaves in the way you want it in the example:

import { flow } from "fp-ts/lib/function";

const result3 = flow(
  f1,
  chain(f2),
  chain(f3),
  chain(f4)
)("X")

There may arise type problems. For example, it is necessary to have the function parameter types of the first function (f1) annotated with explicit types. Also consider, that pipe is seen as the new "blessed way" for compositions by the maintainers.

Upvotes: 7

Related Questions