Helcio Oliveira
Helcio Oliveira

Reputation: 34

Typescript TS2532 - Object is possible undefined

    <Form.Field>
      <label>Rua</label>
      <input name='endereco.rua' value={user.endereco.rua}  onChange={(e)=>handleInputChange(e)} placeholder='Insira sua Rua' />
      {errors.endereco.rua !== '' && <ErrorMessage>{errors.endereco.rua}</ErrorMessage>}

    </Form.Field>

     <Form.Field>
      <label>Numero</label>
      <input name='endereco.numero' type='number'   onChange={(e)=>handleInputChange(e)} placeholder='Insira seu numero' />
      {errors.endereco.numero !==  undefined  && <ErrorMessage>{errors.endereco.numero}</ErrorMessage>}

    </Form.Field>

  export  interface Errors{
    name?: string;
    password?: string;
    email?: string;
    cpf?: string;
    endereco?: {
        cep?: string;
        cidade?: string;
        bairro?: string;
        rua?: string;
        numero?: string;
    }

   }

How can i deactivate this option or solve the issue? It was only now that it gave me this error. Thank you!

error: Typescript TS2532 - Object is possible undefined.

Upvotes: 0

Views: 162

Answers (1)

David
David

Reputation: 218877

We don't know your specific types, but presumably errors or endereco could be undefined. You can handle that with something like this:

{errors && errors.endereco && <ErrorMessage>{errors.endereco.rua}</ErrorMessage>}

If you also want to check that the property itself isn't undefined, similar to how you currently do, just add that to the chain:

{errors && errors.endereco && errors.endereco.rua && <ErrorMessage>{errors.endereco.rua}</ErrorMessage>}

Basically if any value along that chain is undefined then it'll short-circuit the && conditions and nothing will be rendered there. But if all of the values are defined then the <ErrorMessage/> element is rendered.

Upvotes: 1

Related Questions