Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The operand of a 'delete' operator must be optional.ts(2790) While creating a form using Typescript

I don't understand why this error happening. I'm creating a form to submit user email

export const register = createAsyncThunk<
  User,
  RegisterProps,
  {
    rejectValue: ValidationErrors;
  }
>("auth/registerStatus", async (credentials, { rejectWithValue }) => {
  try {
    // Don't POST blank email
    if (!credentials["email"]) {
      delete credentials["email"]; //editor marking in this line there is error.
    }
    const response = await api.post(API_REGISTER, credentials);
    return response.data;
  } catch (err) {
    const error: AxiosError<ValidationErrors> = err;
    if (!error.response) {
      throw err;
    }
    return rejectWithValue(error.response.data);
  }
});

but I am facing this error:

The operand of a 'delete' operator must be optional.ts(2790)

I guess there is some logic error but I need your help to solve this.

like image 855
Faisal Nazik Avatar asked Dec 14 '25 12:12

Faisal Nazik


2 Answers

In your credentials interface or class declaration object, you must mark email as option field using ? mark.

ex:

    interface Credentials {
        email?: string,
        ...
    }
like image 114
Rajitha Udayanga Avatar answered Dec 16 '25 06:12

Rajitha Udayanga


Another solution, we could use the Partial utility type to construct a new type with the properties set to optional before using the delete operator.

credentials: Partial<Credentials> = { ... };
delete credentials["email"];
like image 25
troy Avatar answered Dec 16 '25 05:12

troy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!