Looks great! I think the type of the context value is meant to be IPledgeDataProvider
, since you want to send dispatch
through the context.
You can get rid of the type assertions in the context functions by setting the type of the context to IPledgeDataProvider | undefined
, and switching the default value to undefined
. Your hook already narrows the type to IPledgeDataProvider
for consumers, so no further changes needed there!
const PledgeDataContext = createContext<IPledgeDataProvider | undefined>(
undefined
);
function PledgeDataProvider({ children }: { children: React.ReactNode }) {
// ...
return (
<PledgeDataContext.Provider
value={
// No assertion
{
// ...
}
}
>
{children}
</PledgeDataContext.Provider>
);
}
function usePledgeData() {
const context = useContext(PledgeDataContext);
if (context === undefined)
throw new Error(
"PledgeDataContext was used outside of the PledgeDataProvider"
);
// No assertion
return context;
}
Marked as helpful
@josh76543210
Posted
@markuslewin thank you very much for this feedback!
I have implemented the changes. So if I understand correctly the IPledgeDataProvider
used when creating the context allows me to remove the IPledgeDataProvider
type assertions in the PledgeDataProvider and usePledgeData functions?
@josh76543210 Precisely. Earlier, you had to assert the type to force the compiler to acknowledge the dispatch
function on the object, but with the correct type for createContext
, the compiler can infer those types on its own