Search code examples
react-nativereact-typescriptreact-navigation-v6

Type of route name, route params in React Navigation Typescript


I am using ReactNavigation v6 along with typescript

I have created a helper functions as

export function navigate(routeName, routeParams) {
  navigationRef.current?.navigate(routeName, routeParams);
}

What type should I specify for routeName & routeParams such that it type checks these params correctly?

I have the following types for my StackNavigator

export type StackNavigator = {
  Welcome: undefined;
  Username: undefined;
  Password: undefined;
  ForgotPassword: {id: number};
};

Solution

  • The routeName parameter can be typed using the following type

    type Routes = keyof StackNavigator
    

    But the routeParams will be dynamic. i.e. routeParams will change as per routeName

    It can be

    {id: number} or undefined
    

    So to compute the 2nd parameter on basis of value of 1st parameter we can do the following

    type NavigationArgs = {
      [Route in keyof StackNavigator]: [
        routeName: Route,
        routeParams?: StackNavigator[Route],
      ];
    }[keyof StackNavigator];
    
    export function navigate(...args: NavigationArgs) {
      const [routeName, routeParams] = args;
      navigationRef.current?.navigate(routeName, routeParams);
    }
    

    This will ensure strict type checking