如何为动态扩展的带操作符对象数组编写TypeScript接口
问题分析
你当前的类型定义仅支持单组对比单元,没有覆盖多组拼接时的and字符串场景,也没有对允许的字符串值做限定,因此多组规则时会触发类型错误。
正确类型实现
首先保留原有的IReference基础接口:
interface IReference { reference: string[] }
方案1:宽松校验(满足日常开发需求)
先限定允许出现的字符串范围,再定义coupon数组类型,足够覆盖大部分开发场景:
// 限定允许出现的字符串只能是=或and type AllowedString = '=' | 'and' interface IReferences { // 数组元素只能是IReference对象或者指定的两个字符串 coupon: Array<IReference | AllowedString> }
方案2:严格顺序校验(完全匹配排列规则)
如果需要严格校验数组的排列顺序必须符合「IReference、=、IReference、and」的循环规律,可以用递归元组类型实现:
// 单个对比单元类型:[引用对象, =, 引用对象] type ComparisonUnit = [IReference, '=', IReference] // 递归定义完整coupon数组:第一个是对比单元,后续每一项都是 and + 对比单元的组合 type StrictCouponArray = [ ...ComparisonUnit, ...Array<'and' | IReference | '='> ] interface IReferences { coupon: StrictCouponArray }
类型安全的数组生成函数
配套的生成函数可确保输出的数组自动符合类型要求,和你的需求完全匹配:
const generateCoupon = (array1: string[], string1: string): Array<IReference | '=' | 'and'> => { const result: Array<IReference | '=' | 'and'> = [] array1.forEach((item, index) => { // 非首个对比单元前加and if (index !== 0) { result.push('and') } // 插入当前对比单元 result.push({ reference: [item] }) result.push('=') result.push({ reference: [string1, item] }) }) return result } // 使用示例 const array1 = ['id', 'home', 'address'] const string1 = 'isValid' const references: IReferences = { coupon: generateCoupon(array1, string1) }
内容的提问来源于stack exchange,提问作者Usman Irshad
相关产品推荐
相关产品推荐

