Issue
I am using React Router to handle fetching data and passing it to components.
I am seeing a TypeScript error stating Type 'unknown' is not assignable to type '{ name: string; value: string; }'.
It seems like the error is happening because reasonTypes
is unknown before the data is fetched.
Is don't really see why this is an error though. Once the data exists I want to make sure it is the correct type, but before the data is fetched I don't want to be making this check.
Here is my code declaring this variable
let reasonTypes: {name:string value:string} = useRouteLoaderData('root')
Solution
The useRouteLoaderData hook's return type is unknown
:
/** * Returns the loaderData for the given routeId */ export function useRouteLoaderData(routeId: string): unknown { let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData); return state.loaderData[routeId]; }
You can cast the returned data to the type you require.
Examples:
const reasonTypes = useRouteLoaderData('root') as { name: string; value: string; };
type Data = {
name: string;
value: string;
};
...
const reasonTypes = useRouteLoaderData('root') as Data;
Answered By - Drew Reese
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.