我正在尝试使用 fp-ts 实现一些简单的数据验证,并遇到了这个代码框示例:
import * as E from "fp-ts/lib/Either";
import { getSemigroup, NonEmptyArray } from "fp-ts/lib/NonEmptyArray";
import { sequence } from "fp-ts/lib/Array";
import { pipe } from "fp-ts/lib/pipeable";
import { Predicate } from "fp-ts/lib/function";
type ValidationError = NonEmptyArray<string>;
type ValidationResult = E.Either<ValidationError, unknown>;
type ValidationsResult<T> = E.Either<ValidationError, T>;
interface Validator {
(x: unknown): ValidationResult;
}
interface Name extends String {}
const applicativeV = E.getValidation(getSemigroup<string>());
const validateName: (
validations: Array<Validator>,
value: unknown
) => ValidationsResult<Name> = (validations, value) =>
validations.length
? pipe(
sequence(applicativeV)(validations.map((afb) => afb(value))),
E.map(() => value as Name)
)
: E.right(value as Name);
const stringLengthPredicate: Predicate<unknown> = (v) =>
typeof v === "string" && v.length > 4;
const lengthAtLeastFour: Validator = E.fromPredicate(
stringLengthPredicate,
() => ["value must be a string of at least 5 characters"]
);
const requiredLetterPredicate: Predicate<unknown> = (v) =>
typeof v === "string" && v.includes("t");
const hasLetterT: Validator = E.fromPredicate(requiredLetterPredicate, () => [
'value must be a string that includes the letter "t"'
]);
const validations = [hasLetterT, lengthAtLeastFour];
console.log(validateName(validations, "sim"));
// {left: ['value must be a string that includes the letter "t"', 'value must be a string of at least 4 characters']}
console.log(validateName(validations, "timmy"));
// {right: 'timmy'}
是什么Predicate
?在这个例子中使用它有什么作用?我在文档中没有看到任何关于它的作用的解释,只是它是API 的一部分,并且它似乎修改了提供的接口。