I am currently working with a router array and I would appreciate some TypeScript tips when adding route items. Currently, I am receiving tips on addition but encountering an error when using props.navigate. The component shows an error if not set as any.
Can someone assist me with the TypeScript for this?
Here is my code:
// types.ts
import { StackNavigationProp, StackNavigationState, ParamListBase } from ‘@react-navigation/stack’;
import { RouteProp, StackNavigationOptions, StackNavvigationEventMap } from '@react-navigation/native';
type RootStackParamList = {
Home: undefined;
Profile: { userId: string };
Settings: undefined;
};
export type INavigationType<T extends keyof RootStackParamList> =
StackNavigationProp<RootStackParamList, T>;
export type IRouteType<T extends keyof RootStackParamList> =
RouteProp<RootStackParamList, T>;
export type IStackRouteType =
RouteConfig<
RootStackParamList,
keyof RootStackParamList ,
StackNavigationState<ParamListBase>,
StackNavigationOptions,
StackNavvigationEventMap
>
// index.tsx
import { createStackNavigator } from '@react-navigation/stack';
import { IStackRouteType } from './types;'
const StackNavigator = createStackNavigator<RootStackParamList>();
const stackRoutes: IStackRouteType= [
{
name: 'Home',
component: HomeScreen,
options: {
headerShown: false
}
},
{
name: 'Profile',
component: ProfileScreen, // <----- error
options: {
headerShown: false
},
listeners: () => {
return ({
state: (e) => {
console.log('state changed', e.data);
},
})
}
},
{
name: 'Settings',
component: Settings,
options: {
headerShown: false
}
},
];
export default function App() {
return (
<NavigationContainer>
<StackNavigator.Navigator>
{stackRoutes.map((route, index) => (
<StackNavigator.Screen
key={route.name}
{...route}
/>
))}
</StackNavigator.Navigator>
</NavigationContainer>
);
}
// Profile page
import { INavigationType, IRouteType } from '../types';
interface IProps {
route: IRouteType<'Profile'>;
navigation: INavigationType<'Profile'>;
}
function Profile ({
route,
navigation
}: IProps ) {
const { userId } = route.params;
useEffect(() => {
props.navigate(PageName) // this not tip pageName or page arguments if the page need
}, [])
return (
<Text>this is Profile page</Text>
)
}
Using props.navigation(), it will provide tips on pageName and arguments correctly. Also, the PageComponent will not show errors if not specified as any.