我第一次看pipe
和Option
进去fp-ts
。
我有这段代码,它的类型很窄,但我确信它可以在没有if
语句的情况下完成:
if (O.isNone(this.state)) {
return undefined;
}
return this.lens.get(this.state.value);
我第一次看pipe
和Option
进去fp-ts
。
我有这段代码,它的类型很窄,但我确信它可以在没有if
语句的情况下完成:
if (O.isNone(this.state)) {
return undefined;
}
return this.lens.get(this.state.value);
您可以尝试与andpipe
结合使用:Option.fromNullable
Option.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))
);
通常,所有这些包装数据类型的想法是您不想过早地拆开包装。在你的情况下,考虑到这this.state
是一个Option
,我会这样做:
import { option } from 'fp-ts';
pipe(
this.state,
option.map(state => this.lens.get(state)),
option.toUndefined,
);