繁体   English   中英

如何使用io-ts验证数组长度?

[英]How to validate array length with io-ts?

我正在进行io-ts验证,我想验证列表长度(它必须在最小和最大之间)。 我想知道是否有办法实现这种行为,因为它可以在运行时非常方便地进行 API 端点验证。

到目前为止我所拥有的是

interface IMinMaxArray {
  readonly minMaxArray: unique symbol // use `unique symbol` here to ensure uniqueness across modules / packages
}

const minMaxArray = (min: number, max: number) => t.brand(
  t.array,
  (n: Array): n is t.Branded<Array, IMinMaxArray> => min < n.length && n.length < max,
  'minMaxArray'
);

上面的代码不起作用,它需要Array -s 的参数,并且t.array也不被接受。 我怎样才能以通用的方式使这项工作?

您的定义缺少数组的类型和编解码器。 您可以通过对接口定义进行一些修改并使用编解码器扩展品牌类型来完成这项工作:

interface IMinMaxArray<T> extends Array<T> {
  readonly minMaxArray: unique symbol
}

const minMaxArray = <C extends t.Mixed>(min: number, max: number, a: C) => t.brand(
  t.array(a),
  (n: Array<C>): n is t.Branded<Array<C>, IMinMaxArray<C>> => min < n.length && n.length < max,
  'minMaxArray'
);

现在您可以创建一个定义,如

minMaxArray(3,5, t.number)

如果您希望定义更加通用和可组合,您可以编写一个接受谓词的通用品牌类型:

interface RestrictedArray<T> extends Array<T> {
  readonly restrictedArray: unique symbol
}

const restrictedArray = <C>(predicate: Refinement<C[], ArrayOfLength<C>>) => <C extends t.Mixed>(a: C) => t.brand(
  t.array(a), // a codec representing the type to be refined
  (n): n is t.Branded<C[], RestrictedArray<C>> => predicate(n), // a custom type guard using the build-in helper `Branded`
  'restrictedArray' // the name must match the readonly field in the brand
)

interface IRestrictedArrayPredicate<C extends t.Mixed> {
  (array: C[]): array is ArrayOfLength<C>
}

现在您可以定义您的限制。 分别定义 min 和 max 可能是个好主意,因为它们本身也很有用:

const minArray = <C extends t.Mixed>(min: number) 
  => restrictedArray(<IRestrictedArrayPredicate<C>>((array) => array.length >= min));
const maxArray = <C extends t.Mixed>(max: number)
  => restrictedArray(<IRestrictedArrayPredicate<C>>((array) => array.length <= max));

结合这两者,您可以定义 minMaxArray:

export const minMaxArray = <C extends t.Mixed>(min: number, max: number, a: C) => t.intersection([minArray(min)(a), maxArray(max)(a)])

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM