I’m having some issues with using TypeScript and creating a custom type to pass to navigation.navigate(). I have a prop type called ScreenLink
that looks like this:
interface ScreenLink {
name: string,
dest: keyof RootStackParamList
}
Where RootStackParamList is imported from another file that looks like this:
export type RootStackParamList = {
Root: NavigatorScreenParams<RootTabParamList> | undefined;
Home: undefined;
Landing: undefined;
LogIn: undefined;
// ...etc.
}
export type RootTabParamList = {
Home: undefined;
Settings: undefined;
// ...etc.
};
export type RootStackScreenProps<Screen extends keyof RootStackParamList> = NativeStackScreenProps<
RootStackParamList,
Screen
>;
I then use the custom type in a component like this:
const LinkCard = (props: { index: number, screenLink: ScreenLink }) => {
const handleOnPress = () => {
navigation.navigate(props.screenLink.dest)
}
return (<Pressable onPress={handleOnPress}> </Pressable>)
}
This seems like it should work. When I mouseover the type of ‘dest’ it shows all of the potential keys I want to pass as a route. However, I get an error that “No overload matches this call”:
No overload matches this call.
Argument of type '[keyof RootStackParamList]' is not assignable to parameter of type '[screen: "Root"] | [screen: "Root", params: NavigatorScreenParams<RootTabParamList> | undefined] | [screen: "Home"] | [screen: "Home", params: undefined] | [screen: "Landing"] | [screen: ...] | ... 53 more ... | [screen: ...]'.
Interestingly, the error goes away when I change keyof RootStackParamList
to keyof RootStackParamList['Root']
and the code functions exactly like it should. But I have no idea why this works or what was wrong in the first place.
So far, I’ve been referencing the docs:
https://reactnavigation.org/docs/5.x/typescript/
And this answer:
Type of route name, route params in React Navigation Typescript
But I still can’t figure out what is wrong with the original code. Happy to provide more details if necessary. Thanks.