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

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

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 Relatório

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