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

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

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 Denunciar

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 Denunciar

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 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