您的定义缺少数组的类型和编解码器。您可以通过对接口定义进行一些修改并使用编解码器扩展品牌类型来完成这项工作:
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)])
希望这会有所帮助。