Is there a way to optimize the validateField
function to narrow down the type more effectively?
type TStringValidator = (v: string) => void;
type TNumberValidator = (v: number) => void;
type TFields = 'inn' | 'amount';
interface IValidators {
inn: TStringValidator[];
amount: TNumberValidator[];
}
const handleString: TStringValidator = (value: string) => {};
const handleNumber: TNumberValidator = (value: number) => {};
const validators = {
inn: [handleString],
amount: [handleNumber],
} satisfies IValidators;
function validateField(field: TFields, value: string | number) {
const fieldValidators = validators[field];
for (const validator of fieldValidators) {
// The issue lies here
const result = validator(value);
}
return;
}
Link to the TS playground.
Expect validator(value)
call not to throw TS error:
Argument of type 'string | number' is not assignable to parameter of type 'never'.
Type 'string' is not assignable to type 'never'.(2345)
(parameter) value: string | number
The TypeScript compiler seems to struggle with inferring the type for the dynamic validator based on the field
value.
Perhaps some refactoring of the validateField
function could help.