Reputation: 2863
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.
Upvotes: 17
Views: 28871
Reputation: 4955
delete (credentials as any).email
Not very familiar with typescript, but I bumped into something similar and I solved this way
Upvotes: 5
Reputation: 3778
If you want to disable this behavior, set strictNullChecks
to false in tsconfig.json:
{
"compilerOptions": {
"strictNullChecks": false
}
}
Upvotes: 1
Reputation: 2515
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"];
Upvotes: 5
Reputation: 1732
In your credentials
interface or class declaration object, you must mark email
as option field using ?
mark.
ex:
interface Credentials {
email?: string,
...
}
Upvotes: 13
Reputation: 351
This error happens because you created a class with the mandatory attribute you can work around creating a mirror class with the optional attributes.
class Foo {
aa: string
bb: number
cc: boolean
}
type FooMirror = {aa: string, bb?: number, cc?: boolean}
const foo = new Foo()
const test: FooMirror = foo
delete test.aa // error operator must by optional
delete test.bb // true
delete test.cc // true
Upvotes: 4