Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

590
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda