“删除”运算符的操作数必须是可选的。ts(2790) 使用 Typescript 创建表单时

Fai*_*zik 14 typescript reactjs

我不明白为什么会发生这个错误。我正在创建一个表单来提交用户电子邮件

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);
  }
});
Run Code Online (Sandbox Code Playgroud)

但我面临这个错误:

“删除”运算符的操作数必须是可选的。ts(2790)

我猜有一些逻辑错误,但我需要你的帮助来解决这个问题。

Raj*_*nga 12

credentials接口或类声明对象中,必须email使用 mark 将其标记为选项字段?

前任:

    interface Credentials {
        email?: string,
        ...
    }
Run Code Online (Sandbox Code Playgroud)


tro*_*roy 5

另一种解决方案是,我们可以Partial在使用删除运算符之前使用实用程序类型构造一个新类型,并将属性设置为可选。

credentials: Partial<Credentials> = { ... };
delete credentials["email"];
Run Code Online (Sandbox Code Playgroud)