I have functions to validate forms, I want the function to be in a separate file, but I have a type problem for validationRequirements[fieldName] i getting error Type 'keyof T1' cannot be used to index type '{ name: (value: string) => boolean; }'.
Here is my validations requirements:
const validationRequirements = {
name: (value: string) => false, //mock
}
Interface for createValidationObj:
interface CreateValidationObjI<T1> {
validation: T1
fieldName: keyof T1
value: string
}
Here I call a function to update the validation object, I pass validationI as typescript argument then i use it as generic:
const onChangeValidation = ({ value, fieldName }: { value: string; fieldName: keyof typeof validation }) => {
const validationObj = createValidationObj<validationI>({ validation, fieldName, value })
}
Here is the validation function, I want that function in separate:
const createValidationObj = <T1 extends {}>({ validation, fieldName, value }: CreateValidationObjI<T1>) => ({
...validation,
[fieldName]: {
...validation[fieldName],
isValid: validationRequirements[fieldName](value), <-- Type 'keyof T1' cannot be used to index type '{ name: (value: string) => boolean; }'.
isTouched: true,
},
})
Link to example: Example
T1extends{}rather than the referencedvalidationRequirements?T1extends the interfacevalidationI, the code will not work because that impliesT1may have some extra keys different fromvalidationI. EitherT1must have same or lesser(subset) keys thanvalidationIor assigning might have reverse (but it is not the requirement of the code)