My objective is to prevent repeating multiple times the checks for the existence of the id
or value
in switch cases.
Error Message:
An error occurs when trying to assign a value of type 'string | undefined' to a parameter that requires type 'string'.
The type 'undefined' cannot be assigned to type 'string'.ts(2345)
Code snippet:
export const enum Message {
setItem = 'setItem',
}
function foo(message: Message, data: Partial<Record<string, string>>) {
const isValid = data.id != null && data.value != null;
switch (message) {
case Message.setItem: {
if (isValid) {
setItem(data.id, data.value);
}
}
}
}
const setItem = (id: string, value: string | object) => {
return id + value;
}
I encountered a type error at setItem(data.id, data.value);
Additional Information:
- The function storage.setItem() requires the first argument to be a string.
- The error implies that TypeScript fails to deduce that
event.data.data.id
will always be a string, despite the presence ofisValid
. - In practical terms, I have numerous switch cases where I need to validate the
id
, while in others, it is unnecessary.