In this typescript v4.0, a new specification has been added for delete keyword.
[spec]
When using the delete operator in strictNullChecks, the operand must now be any, unknown, never, or be optional (in that it contains undefined in the type).
Otherwise, use of the delete operator is an error.
I don't understand why this spec added.
Why can't delete specific type ?
I wonder why these specs were added.
I can turn off the "strictNullChecks" option, but that doesn't seem like a good idea.
Thank you.
--- edit ---
[example]
type UserFromDatabase = {
name: string;
password: string;
}
type User = Omit<UserFromDatabase, "password">
const signIn = (): User => {
const userFromDatabase: UserFromDatabase = getUserFromDatabase();
// do something
// compare password ...
delete userFromDatabase.password; // error occured typescript 4.0
const user: User = { ...userFromDatabase };
return user;
}
--- edit2 ---
typescript version : v4.0 [ new spec - delete keyword allow types ]
I know that javascript's delete keyword is deleting object's property not object.
Some object key is available when important logic.
So, after doing important logic, I want to delete object key.
If you could delete something, that means that something might not exist (especially after being deleted), so the type of that something has to allow non-existence. Consider the following example:
In fact, the last line will throw an error in runtime. So it is the right thing to have stricter type check to prevent this kind of runtime error.
Update
So in your case you can do:
Or, as Aluan Haddad pointed out, a more clever way without using
delete
is: