I am currently working on a tab navigator with Home
and Profile
screens. Within the Home
screen, there is a stack navigator containing the RestaurantDetails
and RestaurantList
screens.
My issue lies with a Button
located in the RestaurantList
screen. I am trying to navigate to the RestaurantDetails
screen.
This is the code for Button.tsx:
const Button = ({name}) => {
const navigation = useNavigation()
const onPress = () => {
navigation.navigate("RestaurantDetails", {name})
}
return (
<TouchableOpacity onPress={onPress}>
</TouchableOpacity>
)
}
The problem arises with typescript throwing an error:
Argument of type '["RestaurantDetails", { name: string}]' is not assignable to parameter of type '[screen: "Home", params: NavigatorScreenParams<HomeStackParamList, Readonly<{ key: string; index: number; routeNames: string[]; history?: unknown[] | undefined; routes: NavigationRoute<ParamListBase, string>[]; type: string; stale: false; }>>] | [screen: ...] | [screen: ...] | [screen: ...] | [screen: ...]'.
Type '["RestaurantDetails", { name: string}]' is not assignable to type '[screen: "Profile", params: undefined]'.
Type at position 0 in source is not compatible with type at position 0 in target.
Type '"RestaurantDetails"' is not assignable to type '"Profile"'.
I suspect that typescript is looking in the TRootParamList
instead of HomeStackParamList
for the RestaurantDetails
screen. Adding RestaurantDetails
to
TRootParamList</code resolves the issue but I'm unsure how to prevent this from happening.</p>
<p>Here is the code snippet from types.ts:</p>
<pre><code>import { NavigatorScreenParams } from '@react-navigation/native';
type QueueDetailsParams = {
name: string
};
type HomeStackParamList = {
RestaurantDetails: QueueDetailsParams | undefined;
RestaurantList: undefined
};
type TRootParamList = {
Home: NavigatorScreenParams<HomeStackParamList>;
Profile: undefined
};
declare global {
namespace ReactNavigation {
interface RootParamList extends TRootParamList {}
}
}
P.S. I am aware that I can update my onPress
function as shown below, although I would prefer to find an alternative solution:
const onPress = () => {
navigation.navigate("Home", {screen: "RestaurantDetails", params: {name}})
}