-2

我第一次看pipeOption进去fp-ts

我有这段代码,它的类型很窄,但我确信它可以在没有if语句的情况下完成:

if (O.isNone(this.state)) {
  return undefined;
}

return this.lens.get(this.state.value);
4

2 回答 2

2

您可以尝试与andpipe结合使用:Option.fromNullableOption.map

import { pipe } from "fp-ts/function";
import * as O from "fp-ts/Option";

let obj = {
  state: {
    value: "test"
  }
};

function calculate(input: { value: string }) {
  return input.value;
}

console.log(
  pipe(
    obj.state,
    O.fromNullable,
    O.map((value) => calculate(value))
  )
);

因此,对于您的示例,它将类似于:

return pipe(
  this.state,
  O.fromNullable,
  O.map(state => this.lens.get(state.value))
);
于 2020-11-22T11:40:00.653 回答
2

通常,所有这些包装数据类型的想法是您不想过早地拆开包装。在你的情况下,考虑到这this.state是一个Option,我会这样做:

import { option } from 'fp-ts';

pipe(
  this.state,
  option.map(state => this.lens.get(state)),
  option.toUndefined,
);
于 2020-11-22T23:59:34.567 回答