I have a react hook below which will return item route properties from a react navigation route. I currently use the type CartRouteProps which in turn uses the specific RouteName "CartScreen". This works but I have multiple routes which have item props and I would prefer to make it more generic and allow any route with properties that extend ItemProps.
Is there a way where I can use Typescript Generics to restrict the RouteName to only routes who's value extends ItemProps?
Navigator.tsx
type ItemProps = {
id: number
}
type AppStackParamList = {
MainScreen: undefined;
ResultsScreen: undefined;
OrderScreen: ItemProps;
CartScreen: ItemProps;
PaymentScreen: ItemProps;
ConfirmationScreen: undefined;
};
...
useItem.hook.ts
import { RouteProp, useRoute } from "@react-navigation/native";
import { AppStackParamList } from "../Navigator";
export type CartRouteProps = RouteProp<
AppStackParamList,
"CartScreen"
>;
export const useItem = () => {
const route = useRoute<CartRouteProps>();
const itemParams = route.params;
return itemParams;
};