My goal is to avoid repeating many times in switch cases of such checks of the existence of the id
or value
Error Message:
The argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable 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'm getting a type error within setItem(data.id, data.value);
Additional Information:
- storage.setItem() expects the first argument to be a string.
- The error seems to suggest that TypeScript is not able to infer that
event.data.data.id
is always a string, even thoughisValid
should ensure this. - In practice I have many of these switch cases in some of them I need to check
id
in others I don't