A common error which occurs in react-navigation
, when using TypeScript, is:
Argument of type ‘string’ is not assignable to parameter of type ‘{ key: string; params?: undefined; merge?: boolean | undefined; } | { name: never; key?: string | undefined; params: never; merge?: boolean | undefined; }’
What could this be caused by?
Advertisement
Answer
This occurs when types for specific screens have not been defined.
I will describe setting up types for the stack navigation, usage in the useNavigation
hook, as well as passing the {navigation}
through props to a screen.
First, setup the Stack Navigator:
/**
* Types for Stack Navigator.
*/
export type StackParamList = {
Main: undefined;
Home: undefined;
};
const Stack = createStackNavigator<StackParamList>();
When using the useNavigation
hook:
import { StackNavigationProp } from "@react-navigation/stack";
/**
* Types for the Stack Navigator.
*/
export type StackNavigation = StackNavigationProp<StackParamList>;
const navigation = useNavigation<StackNavigation>();
When passing the navigation down as a prop in a screen:
/**
* Types for passing the navigation props to screens in the Stack Navigator.
*/
export type StackNavigationProps = {
navigation: StackNavigation;
};
const SomeScreenInTheStack = ({ navigation }: StackNavigationProps) => {
}
I extended the answer in another question, just like this, but come to find the OP is not tagging the post correctly so I created this Q&A.
Hope this is useful to someone!