I have a union type Actions which is
type Actions = Readonly<{
type: ActionTypes.LOAD_POST;
payload: string;
}> | Readonly<{
type: ActionTypes.LOAD_POST_FAIL;
payload: string;
}> | Readonly<{
type: ActionTypes.LOAD_POST_SUCCESS;
payload: {
url: string;
post: Post;
};
}>
(This is the generated type, the original was nested with multiple types and ReturnType.) ActionTypes is a string enum.
const postReducer = (state = initialPostState, action: Actions): PostState => {
const { type, payload } = action;
switch (action.type) {
case ActionTypes.LOAD_POST_SUCCESS: {
const { post } = action.payload; // No error
return { ...state, loading: false, success: true, post };
}
}
switch (type) {
case ActionTypes.LOAD_POST: {
return { ...state, loading: true };
}
case ActionTypes.LOAD_POST_SUCCESS: {
// [ts] Type 'string | { url: string; post: IFullPost; }' has no property 'post' and no string index signature.
const { post } = payload;
return { ...state, loading: false, success: true, post };
}
case ActionTypes.LOAD_POST_FAIL: {
return { ...state, loading: false, success: false, post: null };
}
default:
return state;
}
};
Why does the first one work but not the second one?