'How to use typescript generics to restrict a type to keys of an object who's value extends a given type
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;
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
