Home > Mobile >  typescript - fp ts How to choose a result according of an Option
typescript - fp ts How to choose a result according of an Option

Time:11-05

I'm trying to choose between two possible strings according if an Option is Some or None. When option is Some, everything runs correctly, but when it's none, I'm getting a weird error.

import { option } from "fp-ts";
import { pipe } from "fp-ts/function";

pipe(
  option.none, // with option.some("defaultId") works smoothly
  option.foldW(
    () => {
      return "default string";
    },
    (id) => {
      return this.findStringById(id);
    },
  ),
...

Said error:

{ message: "Cannot read properties of undefined (reading '_tag')" }

I've tried with option.matchW also, and boolean.foldW, but the first has the same problem and the second doesn't give me access to the inside of Some

Thanks in advance!

CodePudding user response:

The following examples should work. I'm using fp-ts 2.11.8. I actually think the issue here may be elsewhere and not related to the option usage. Are you trying to lift this value into another ADT after this call to pipe?

import { pipe } from 'fp-ts/lib/function';
import * as O from 'fp-ts/lib/Option';
import { option } from 'fp-ts';

// mocked function
const findStringById = id => `finding ${id}`;

pipe(
  O.none,
  O.foldW(
    () => 'default return value',
    (id) => findStringById(id),
  )
); // -> 'default return value'

pipe(
  option.none,
  option.foldW(
    () => 'default return value',
    (id) => findStringById(id),
  )
); // -> 'default return value'

pipe(
  O.some('1234'),
  O.foldW(
    () => 'default return value',
    (id) => findStringById(id),
  )
); // -> 'finding 1234'
  • Related