Is there a way to properly type an initial value in a useReducer hook using a discriminating union?
I am passing an initial value into my context that can either be an object of Dog or Turtle. I am getting an No overload matches this call error because there are properties that exist in Dog and not Turtle and vice versa.
type Dog = {
name: string;
breed: string;
tail: number;
}
type Turtle = {
name: string;
breed: string;
spots: number
}
type AnimalItem = Turtle | Dog;
export type Props = Readonly<{
initialValue: AnimalItem;
type: AnimalType;
}>;
export const CardConfigEditContextProvider: React.FC<
PropsWithChildren<Props>
> = ({ children, initialValue, type }: PropsWithChildren<Props>) => {
const reducer = getAnimalReducer(type);
// getting an error overload matches this call error
const [state, dispatch] = useReducer(reducer, initialValue);
return (
<CardConfigEditContext.Provider value={{ state, dispatch }}>
{children}
</CardConfigEditContext.Provider>
);
};