Question
I have a reducer model with an action that accepts a payload expecting a shape of { id: string, newValues: Partial<A_or_B> }. In the code below, the enforcement of type A_or_B is not enforced when I declare newValues inline; however, if I declare newValues ahead of time and assign properties to it, the constraints are enforced. How can I enforce the constraints on A_or_B even when newValues is declared inline?
Problematic Code
import { useContext } from "react";
import { AppDispatchContext } from "../src/AppProvider";
import { ActionTypes, A_or_B } from "./interfaces";
export default function App() {
const dispatch = useContext(AppDispatchContext);
const x: Partial<A_or_B> = {};
// Property 'color' does not exist on type
// 'Partial<A> | Partial<B>'.
// Property 'color' does not exist on type 'Partial<A>'.
x.color = "red";
dispatch({
type: ActionTypes.POINT_UPDATED,
// why can I assign a color to Partial<A>|Partial<B> if 'color'
// only exists on B?
payload: { id: "x", newValues: { color: "red" } }
});
}