typescript - 什么是 fp-ts 谓词?

标签 typescript fp-ts

我正在尝试使用 fp-ts 实现一些简单的数据验证,并遇到了这个 codesandboxexample :

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'}

什么是谓词?这个例子中使用它的效果如何?我在文档中没有看到它的作用的任何解释,只是它是 part of the API并且它似乎修改了提供的接口(interface)。

最佳答案

Predicate<A> = (a:A) => boolean

谓词是一个接受参数并返回 bool 值的函数。这是 filter 所采用的类型以及 fromPredicate属于多种类型,例如 Option 和 Either。

例如,

import { filter } from 'fp-ts/Array'
import { pipe } from 'fp-ts/function'
import { fromPredicate } from 'fp-ts/Either'

const errorIfNotThree = fromPredicate<number>(x => x===3, () => 'not three!')
const f = pipe([1,2,3], filter(x => x===3))

errorIfNotThree(3) // right(3)
errorIfNotThree(5) // left('not three!')
f // [3]

在上面,x => x===3类型为Predicate<number>因为它是一个接受数字并返回 bool 值的函数

关于typescript - 什么是 fp-ts 谓词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67481116/

相关文章:

typescript - fp-ts在mapLeft内部调用异步函数

typescript - OO 到函数式——从日常问题中学习

typescript - 在 fp-ts 中,如何组合 2 个(或更多)Ord 实例

typescript - 在 Visual Studio 中使用 angular2

node.js - 无法使用 Typescript 和 NodeJS 从绝对路径导入

c# - 如何将 Typescript Map 对象发布到 ASP.Net Core WebAPI?

angular - 在 Android 模拟器上运行 Ionic4/Capacitor 时如何调试 .ts 文件

typescript - NativeScript 应用程序为 "Error-ReferenceError-ErrorEvent is not defined"

javascript - TaskEither sequenceArray 函数处理不同类型返回类型的问题