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

268
Vistas
When I try to destructure my state object in react typescript, I get an `Object is possibly 'undefined'` error

When I try to destructure my state object in react typescript, I get an Object is possibly 'undefined' error. If I use optional chaining I got this error const newUser: NewUser | undefined Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.

The error is showing when I am trying to destructure object RegisterUser(newUser?.email, newUser?.password, newUser?.name, navigate)

My Code:

type NewUser ={
    name: string,
    email: string,
    password: string,
    navigate: string
}


const Register = () => {
    const [newUser, setNewUser] = useState<NewUser>() // single object will return
  
    const [RegisterUser] = UseFirebase()
    const navigate = useNavigate()

    const handleValues = (e: any) => {
        const field = e.target.name;
        const value = e.target.value
        const user: any = { ...newUser }
        user[field] = value
        setNewUser(user)

    }

    const handleRegister = (e: any) => {
        e.preventDefault()
        // ERROR
        RegisterUser(newUser.email, newUser.password, newUser.name, navigate)
        // console.log('user name', newUser.name, newUser.email, newUser.password);
    }
.......

Could someone please tell me what type of mistake I made?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Well that the typescript for yaa, you need to check first that you will not get undefined as a value by simply doing condition check like this

const handleRegister = (e: any) => {
        e.preventDefault()
        if (newUser?.email && newUser?.password && newUser?.name) {
        RegisterUser(newUser.email, newUser.password, newUser.name, navigate)
        } else { 
// show some error handling here or error to user that he didnt enter value etc
 }
    }
about 4 years ago · Juan Pablo Isaza Denunciar

0

If your object is not undefined, you should try

   RegisterUser(newUser!.email, newUser!.password, newUser!.name, navigate)
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