I'm struggling to find a solution for typing a wrapper function. My goal is to enhance a form control's onChange
callback by adding a console.log
. Can someone please point out what I might be overlooking?
interface TextInput {
type: 'TextInput';
onChange: (value: string) => void;
}
interface NumberInput {
type: 'NumberInput';
onChange: (value: number) => void;
}
type FormControl = TextInput | NumberInput;
export const withLogger = <TFormControl extends FormControl>(formControl: TFormControl): TFormControl => ({
...formControl,
onChange: (...args: Parameters<TFormControl['onChange']>) => {
console.log(formControl.type, 'onChange', args);
// Issue: A spread argument must either have a tuple type or be passed to a rest parameter.(2556)
return formControl.onChange(...args);
},
});
I've tried various ways of defining the arguments for the onChange wrapper such as:
onChange: (value: any) => formControl.onChange(value)
onChange: <TValue>(value: TValue) => formControl.onChange(value)
onChange: (value: number | string) => formControl.onChange(value)
However, all these attempts result in an error message:
Argument of type 'string | number' is not assignable to parameter of type 'never'. Type 'string' is not assignable to type 'never'.(2345)