import { InputProps as MUIInputProps } from '@mui/material'; import { Dispatch, SetStateAction } from 'react'; import MAP_TO_VALUE_CONVERTER from './consts/MAP_TO_VALUE_CONVERTER'; type CreateInputOnChangeHandlerTypeMap = Pick; type InputOnChangeParameters = Parameters< Exclude >; type MapToStateSetter = { [TypeName in keyof CreateInputOnChangeHandlerTypeMap]: Dispatch< SetStateAction >; }; type CreateInputOnChangeHandlerOptions< TypeName extends keyof CreateInputOnChangeHandlerTypeMap, > = { postSet?: (...args: InputOnChangeParameters) => void; preSet?: (...args: InputOnChangeParameters) => void; set?: MapToStateSetter[TypeName]; setType?: TypeName | 'string'; }; const createInputOnChangeHandler = ({ postSet, preSet, set, setType = 'string', }: CreateInputOnChangeHandlerOptions = {}): MUIInputProps['onChange'] => (event) => { const { target: { value }, } = event; const postConvertValue = MAP_TO_VALUE_CONVERTER[setType]( value, ) as CreateInputOnChangeHandlerTypeMap[TypeName]; preSet?.call(null, event); set?.call(null, postConvertValue); postSet?.call(null, event); }; export type { CreateInputOnChangeHandlerOptions, InputOnChangeParameters, MapToStateSetter, }; export default createInputOnChangeHandler;