This question resembles this how to use navigation.replace in TypeScript? which is for react-navigation 5.
I also read the docs https://reactnavigation.org/docs/typescript/#annotating-usenavigation
Tried a couple of different ways, but got more confused 🙃.
import { BottomTabScreenProps } from '@react-navigation/bottom-tabs'
import { CompositeScreenProps, NavigatorScreenParams } from '@react-navigation/native'
import { NativeStackScreenProps } from '@react-navigation/native-stack'
import { AxiosError } from 'axios'
declare global {
namespace ReactNavigation {
interface RootParamList extends RootStackParamList {}
}
}
export type RootStackParamList = {
SignIn: undefined
ResetPassword: { email?: string } | undefined
Root: NavigatorScreenParams<RootTabParamList> | undefined
Modal: undefined
Error: { error?: AxiosError | null } | undefined
DevToolsSignIn: undefined
}
export type RootTabParamList = {
Overview: undefined
Returns: undefined
Portfolio: undefined
More: undefined
}
export type RouteName = keyof RootStackParamList | keyof RootTabParamList
export const routeTypeGuard = (route: RouteName) => route as keyof RootStackParamList
export type RootStackScreenProps<Screen extends keyof RootStackParamList> = NativeStackScreenProps<
RootStackParamList,
Screen
>
export type RootTabScreenProps<Screen extends keyof RootTabParamList> = CompositeScreenProps<
BottomTabScreenProps<RootTabParamList, Screen>,
NativeStackScreenProps<RootStackParamList>
>
then in a component I wish to tell typescript that I should be able to destruct replace from the useNavigation()
export default ({ route }: RootStackScreenProps<'ResetPassword'>) => {
const { replace } = useNavigation<?🙃?>()
const email = route.params?.email
if (!email) replace('Error')
return (
<ScreenContainer>
<Text style={{ color: 'hotpink' }}>{email}</Text>
</ScreenContainer>
)
}
this seems to do the trick
const { navigate, replace } = useNavigation<NativeStackNavigationProp<RootStackParamList>>()
that allows me to do things like:
replace('Root')
without any TS issues.
My misunderstanding was that the replace can't replace to any screen it wants - it can only replace to any screen within the navigation it's in.