When it comes to typing screens under react-navigation v5, I usually follow a simple pattern:
// Params definition
type RouteParamsList = {
Screen1: {
paramA: number
}
Screen2: undefined
}
// Screen1
type Props = StackScreenProps<RouteParamsList, 'Screen1'>
export const Screen1: React.FC<Props> = ...
It works perfectly for most cases.
However, I'm facing a challenge when trying to reuse the Screen1
component for different navigators:
// Params definition
type RouteParamsListShop = {
Screen1: {
paramA: number
}
Screen2: undefined
Screen3: undefined
}
type RouteParamsListFeatures = {
Screen1: {
paramA: number
}
Screen4: undefined
}
// Screen1
type Props = StackScreenProps<RouteParamsListShop, 'Screen1'> | StackScreenProps<RouteParamsListFeatures, 'Screen1'> // Attempted solution
export const Screen1: React.FC<Props> = ...
Although using a union type allows me to extract parameters from the route correctly, the navigation method navigate
poses an issue:
This expression is not callable. Each member of the union type '/* Route info here */' has signatures, but none of those signatures are compatible with each other.ts(2349)
Is there a way to properly address this typing issue, or should I consider restructuring my navigation setup to have the screen associated with only one route? Alternatively, creating two wrappers for different navigation instances may be another option.