Getting 'not assignable' in TS with Generic type

Viewed 48

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;
};
1 Answers
Related