I have a problem with understanding of Typescript type describing my validation functions. These are the types of functions that I use with my code:
type ValidationFunctionType = {
fieldName: string;
fields: string;
};
type MaxYearType = ValidationFunctionType & { fieldValue: Date; args: { maxYear: Date } };
type MinLengthType = ValidationFunctionType & {
fieldValue: string;
args: { minLength: number };
};
type MinNumberType = ValidationFunctionType & {
fieldValue: number;
args: { minNumber: number };
};
Then I create a union type for all the functions:
export type ValidationFunctionsType =
| (({}: MinLengthType) => string)
| (({}: MinNumberType) => string)
| (({}: MaxYearType) => string);
These are the functions that I use with these function types:
const minLength = ({ fieldName, fieldValue, fields, args }: MinLengthType) => {
return '';
};
const maxYear = ({ fieldName, fieldValue, fields, args }: MaxYearType) => {
return '';
};
const minNumber = ({ fieldName, fieldValue, fields, args }: MinNumberType) => {
return '';
};
And when I create an array with the above functions and use them in map:
const validationFunction: { func: ValidationFunctionsType}[] = [{
func: minLength
}, { func: maxYear}];
validationFunction.map(data => data.func({ fieldName: 'adfa', fieldValue: 'asdda', fields: 'sd', args: {
minLength: 5
} }));
I get the error message for field fieldName:
(property) fieldValue: never Type 'string' is not assignable to type 'never'.(2322) input.tsx(9, 2): The expected type comes from property 'fieldValue' which is declared here on type 'ValidationFunctionType & { fieldValue: string; args: { minLength: number; }; } & { fieldValue: number; args: { minNumber: number; }; } & { fieldValue: Date; args: { ...; }; }'
And for args field:
(property) args: { minLength: number; } & { minNumber: number; } & { maxYear: Date; } Type '{ minLength: number; }' is not assignable to type '{ minLength: number; } & { minNumber: number; } & { maxYear: Date; }'. Property 'minNumber' is missing in type '{ minLength: number; }' but required in type '{ minNumber: number; }'.(2322)
Why these types for field args and fieldName are connected with & operator instead of | operator? How to create a type for these functions which will be correct and more generic?
The whole code example in TS playground: Code
UPDATE
What I want to achieve in this example is to have a correctly designed type for all functions used for validation.
This type seems to work for Typescript:
type ValidationFunctionType = ({fieldName, fields, fieldValue, args}: MinLengthType | MinNumberType | MaxYearType) => string;
Working example But I'm not sure if it is the correct solution. Every function needs validation of fieldName and args type at the beginning.