I'm new to TypeScript and I'm trying to build a custom React hook to store some input (and update it accordingly). I want to make it more general by letting the hook/function store the input as string or number. But as of now in the onChange function, when setting the state I get the following error: Argument of type 'string' is not assignable to parameter of type 'SetStateAction<T>'.
I do understand whats wrong but I have no idea how to fix it. I know I can make two separate functions, but where's the fun in that ;D .
It should be used like this:
const inputNumber = useInput<number>(1);
return(<input
type="text"
value={inputNumber.value}
onChange={inputNumber.onChange}
/>);
Here's my code:
import { useState } from "react";
export default function useInput<T extends string | number>(
init: T
): useInputT<T> {
const [input, setInput] = useState<T>(init);
function onChange(e: React.ChangeEvent<HTMLInputElement>): void {
switch (typeof init) {
case "string":
setInput(e.target.value);
break;
case "number":
setInput(parseInt(e.target.value));
break;
}
}
return { value: input, onChange };
}
type useInputT<T> = {
value: T;
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
};
CodePudding user response:
The problem is typeof e.target.value !== T
. Your setInput is expecting you to set it to type T. In your setInput calls you can cast it as T
to get around that. EX setInput(e.target.value as T)
Here is a little codesandbox https://codesandbox.io/s/interesting-poincare-6h3d5o?file=/src/App.tsx