React Navigation custom route params and typescript

Viewed 49

I have an Error screen that needs to know the error number and a description to display the error and I can't figure out how to tell TS which types are my Error screen custom params. I'm calling my Error screen this way.

  navigation.dispatch(
    StackActions.replace('Error', {
      statusCode: 400,
      description: 'Error description',
    }),
  );

This is my Error screen component. TS complains in route.params

export default function ErrorScreen({ route, navigation }: RootStackScreenProps<'Error'>) {
  const { statusCode, description } = route.params; <-- TS error here
  // @ts-ignore
  const { setClientURL } = appState(({ setClientURL }) => ({
    setClientURL,
  }));

TS2339: Property 'description' does not exist on type 'Readonly { key: string; index: number; routeNames: string[]; history?: unknown[] | undefined; routes: NavigationRoute []; type: string; stale: false; }>> | undefined>'.

These are my types definitions

import { NavigatorScreenParams } from '@react-navigation/native';
import { NativeStackScreenProps } from '@react-navigation/native-stack';

export type RootStackParamList = {
  Root: undefined;
  Error: NavigatorScreenParams<ErrorParamList> | undefined;
  Notifications: undefined;
  Log: undefined;
};

export type RootStackScreenProps<Screen extends keyof RootStackParamList> = NativeStackScreenProps<
  RootStackParamList,
  Screen
>;

export type ErrorParamList = {
  Error: {
    statusCode: number;
    description: string;
  };
};

This is my navigator create code

export default function Navigation({ colorScheme }: { colorScheme: ColorSchemeName }) {
  return (
    <NavigationContainer
      linking={LinkingConfiguration}
      theme={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
      <RootNavigator />
    </NavigationContainer>
  );
}

/**
 * A root stack navigator is often used for displaying modals on top of all other content.
 * https://reactnavigation.org/docs/modal
 */
const Stack = createNativeStackNavigator<RootStackParamList>();

function RootNavigator() {
  const colorScheme = useColorScheme();

  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Error"
        component={ErrorScreen}
        options={({ navigation }: RootStackScreenProps<'Error'>) => ({
          headerLeft: () => null,
          title: 'Ups!...',
          headerShadowVisible: false,
          headerStyle: {
            backgroundColor: '#ffe56d',
          },
          headerTitleStyle: {
            fontWeight: 'bold',
            fontSize: 30,
          },
          gestureEnabled: false,
          headerBackVisible: false,
        })}
      />

How can I tell TS that for my Error screen route.params can have statusCode and description primitives?

0 Answers
Related