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

98
Visualizações
React useState with typescript

I have this code

interface AccountData {
  country: number |null;
}
const [accountData, setAccountData] = useState<AccountData>({ country:null });

Until we assign a value to a country it can be an undefined, null, or empty string.

Then I set the country value like this

const handleChange = (e: number) => {
  if(!isNaN(e)) {
    setAccountData({ country: e });
  }
};

And then I try to pass the value of the country to a function that requires the parameter as a number, I got this error

<Button
  small
  onClick={() => { handleSubmit(accountData.country); }}
>
  save
</Button>

Type 'null' is not assignable to type 'number'.

Which make sense typescript assumes this can be null sometimes. So I check if this is a number before I pass to the function like this

onClick={() => {
  if(!isNaN(accountData.country)) {
    handleSubmit(accountData.country);
  }
}}

But the error is still there. How can I fix this?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Without seeing your handleSubmit function, I'm guessing it's annotated with number. There is a chance country can be null when this is submitted. Therefore TypeScript isn't happy with this.

Something like this might help:

const handleSubmit = (input: number | null) => {
  // stuff
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use as keyword to specify type number for country.

<Button
 small
 onClick={() => {
 handleSubmit(accountData.country as number);
}}>save</Button>

Refer: Type Narrowing

about 4 years ago · Juan Pablo Isaza Relatório

0

If Counrt your value undefined, null, or empty string so can define also any. Which can accept undefined, null, or empty.

Learn more about typescript

interface AccountData {
    country: number | null | any;
}

const [accountData, setAccountData] = useState<AccountData>({ country:null });

const handleSubmit = (input: number | null | any) => {
   // do some stuff here
}
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