Hey there, I've been exploring ways to restrict a function parameter so that it only accepts "strings" related to interface properties, similar to what I achieved in the validate fields function:
Please note: The TypeScript code provided here is simply for illustration purposes.
index.d.ts
export interface FieldErrors {
errors: Array<FieldError>;
}
export type FieldsErrors<TForm> = {
[k in keyof TForm]: FieldErrors;
}
export interface ValidateFieldsCallback<TForm> { (fieldsErrors: FieldsErrors<TForm>, values: TForm): void; };
export interface FormShape<TForm> {
getFieldValue(fieldName: 'documentNumber' | 'userName'): void; // HOW TO FIX THIS
validateFields(callback: ValidateFieldsCallback<TForm>): void;
validateFields(fieldsNames: Array<string>, callback: ValidateFieldsCallback<TForm>): void;
}
example.ts
interface SignupForm {
documentNumber: number;
userName: string;
}
const testForm = <FormShape<SignupForm>>{};
testForm.validateFields((values) => {
console.log(values.documentNumber); // OK
console.log(values.userName); // OK
console.log(values.other); // ERROR
});
// THIS SHOULD BE FIXED
const documentNumber = testForm.getFieldValue('documentNumber');
From the example above, you can see that while I have managed to define the parameter fieldsErrors in the validateFields callback, I now need to address the getFieldValue function to only accept a "valid" field name corresponding to the interface properties, and also return the appropriate type based on the interface rather than void.
I would greatly appreciate any assistance with this matter.