如何根据父键为对象方法指定参数类型(TypeScript表单验证场景)
解决FormRules泛型的字段类型绑定问题
你当前的写法会让验证函数参数变成所有字段类型的联合,原因是FieldsT[keyof FieldsT]会取FormFields里所有值类型的集合。要实现每个字段的验证函数参数对应自身类型,需要用映射类型来逐个处理每个字段:
type FormRules<FieldsT extends object, ValidationRulesT extends string> = { [K in keyof FieldsT]?: Partial<Record<ValidationRulesT, (value: FieldsT[K]) => boolean>> }
为什么这个写法有效?
[K in keyof FieldsT]:遍历FieldsT的每个键,把每个键单独作为类型变量KFieldsT[K]:针对当前键K,精准获取对应的字段类型(比如phone对应number,password对应string)- 外层的
?和Partial:保持原有的可选性,允许部分字段或部分验证规则不定义
验证效果
现在你的formValidationRules中:
phone下的验证函数参数value会被自动推断为numberpassword下的验证函数参数value会被自动推断为string
完整代码示例:
type FormFields = { phone: number password: string } type ValidationRule = 'EMPTY' | 'MIN_LENGTH' type FormRules<FieldsT extends object, ValidationRulesT extends string> = { [K in keyof FieldsT]?: Partial<Record<ValidationRulesT, (value: FieldsT[K]) => boolean>> } // 示例验证函数 const isPhoneLengthValid = (phone: number) => phone.toString().length === 11 const isPhoneEmpty = (phone: number) => phone === 0 || phone.toString().trim() === '' const isPasswordEmpty = (password: string) => password.trim() === '' const formValidationRules: FormRules<FormFields, ValidationRule> = { phone: { EMPTY: (value) => isPhoneEmpty(value), // value类型为number MIN_LENGTH: (value) => isPhoneLengthValid(value) // value类型为number }, password: { EMPTY: (value) => isPasswordEmpty(value) // value类型为string } }
内容的提问来源于stack exchange,提问作者Max Pavlov
相关产品推荐
相关产品推荐

