Currently, I am working on testing the validation logic for a form that primarily consists of simple text fields. However, there are certain fields that have different types of values or require additional logic to set their value. To handle this, I have created an overloaded helper function with the following structure:
type FieldSetter<T> = (field: Field, value: T) => void; // utility functions to set field values
// For the most common case where the value is a string and both valueToTry and setFieldValue are optional
function testFieldValidation(
field: Field,
valueToTry?: string,
setFieldValue?: FieldSetter<string>
): void;
// For less common cases where the value is not a string and both valueToTry and setFieldValue are required
function testFieldValidation<T>(
field: Field,
valueToTry: T,
setFieldValue: FieldSetter<T>
): void;
// Function implementation
function testFieldValidation(
field: Field,
valueToTry = '',
setFieldValue = defaultStringSetter
): void {/* ... */}
I am currently struggling to determine the appropriate type for the second and third arguments in the implementation of testFieldValidation
. I have attempted a few approaches which unfortunately did not yield the desired results:
// Error: '""' can be assigned to the constraint of type 'T', but 'T' may actually represent a different subtype of constraint '{}'
// This does not align with how type parameters work, refer to https://github.com/microsoft/TypeScript/issues/21521
// It would be helpful if TypeScript could infer this from the overloads as safe
function testFieldValidation<T = string>(
field: Field,
valueToTry: T = '',
setFieldValue: FieldSetter<T> = defaultStringSetter
): void {/* ... */}
// Error: this signature clashes with the first overload
function testFieldValidation(
field: Field,
valueToTry: unknown = '',
setFieldValue: FieldSetter<unknown> = defaultStringSetter
): void {/* ... */}
My goal is to avoid using any
unless absolutely necessary. Does anyone have any suggestions or ideas?
While there is a relevant GitHub issue discussing similar concerns, no concrete solutions have been proposed yet: link