Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

264
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!