如何在 fp-ts 中使用管道删除 if 语句
how to use pipe in fp-ts to remove if statement
我第一次在 fp-ts
中查看 pipe
和 Option
。
我有这段代码,它的类型很窄,但我确信它可以在没有 if
语句的情况下完成:
if (O.isNone(this.state)) {
return undefined;
}
return this.lens.get(this.state.value);
您可以尝试将 pipe
与 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,
);
我第一次在 fp-ts
中查看 pipe
和 Option
。
我有这段代码,它的类型很窄,但我确信它可以在没有 if
语句的情况下完成:
if (O.isNone(this.state)) {
return undefined;
}
return this.lens.get(this.state.value);
您可以尝试将 pipe
与 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,
);