Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

593
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda