I have a hook that accepts a type:
type TJsonData = {
message: string;
activity: string;
};
But this type can be on three different levels, so it can accept either:
{ message: "", activity: "" }{ someData: { message: "", activity: "" } }{ errors: { someError: { message: "", activity: "" } } }
I managed to make this work without any errors with:
type TLoaderData =
| TJsonData
| Record<string, TJsonData>
| {
errors?: Record<string, TJsonData>;
};
The problem is, inside the hook it can't properly determine the correct type, at least with my current implementation:
function useActionNotify(...actions: Array<TLoaderData | undefined>) {
//...
useEffect(() => {
actions.forEach((action) => {
if (!action) return;
if (
action.activity // Error here
) {
return notify(action);
}
Object.values(action).forEach((data) => {
if (data.activity) {
return notify(data);
}
// Data errors will be another object to be looped over
Object.values(data).forEach((error) => {
notify(error);
});
});
});
}, [actions, notify]);
}
With the above it gets a type error (or something similar):
Property 'activity' does not exist on type 'TLoaderData'.
Property 'activity' does not exist on type '{ errors?: Record<string, TJsonData> | undefined; }'.ts(2339)
How do I make it get the correct type? Is there any other way other than to force typecast, or is my TLoaderData wrong to begin with?
Codesandbox for the other errors and full implementation: https://codesandbox.io/s/wizardly-faraday-jxjirf?file=/src/App.tsx