Reputation: 11
I have such code:
if (action?.notificationKey && state.notifications[action.notificationKey]) {
delete state.notifications[action.notificationKey];
}
which does not satisfy me, because action.notificationKey can have 0 value and optional chaining condition is not fulfilled.
refactoring to:
if ("notificationKey" in action && state.notifications[action.notificationKey]) {
delete state.notifications[action.notificationKey];
}
does not satisfy TS, and it underlines second condition as "TS2538: Type 'undefined' cannot be used as an index type"
how else I can check property with possible zero value existence?
edit: modified my question as I pasted previous code version, added optional chaining as it is currently
Upvotes: 0
Views: 255
Reputation: 1928
The ?? (Nullish Coalescing) that can be used to set a default value if undefined or null should satisfied your requirements and both typescript with the first version a bit modified
I think it was introduced exactly for this cases. Please not that in order to work indeed you can get rid of the &&
if ((action?.notificationKey) ?? state.notifications[action.notificationKey]) {
delete state.notifications[action.notificationKey];
}
Nullish coalescing operator (??)
So the if will be evaluated always( also when the value of nofiticationkey is 0) except when the first is null or undefined
Upvotes: 0