Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

599
Views
Getting 'not assignable' in TS with Generic type

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;
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!