Here is a simplified version of the code I am working with:
type Todo = {
id: string;
text: string;
};
type Action =
| { type: 'DELETE'; payload: string }
| { type: 'CREATE'; payload: Todo }
function reducer(state: Todo[], { type, payload }: Action) {
switch (type) {
case 'CREATE':
const trimmedText = payload.text.trim(); // TypeScript Error - Property 'text' does not exist on type 'string'
return [...state, payload];
case 'DELETE':
return state.filter((todo) => todo.id !== payload); // TypeScript still thinks, at this line, that the payload could be either string or Todo
default:
throw new Error();
}
}
Some Questions I have:
Why is Typescript not recognizing that in the case of 'CREATE', the payload cannot be a string?
And why doesn't Typescript recognize that in the case of 'DELETE', the payload must be a string?