Skip to content

navigate method type error #11039

@thormengkheang

Description

@thormengkheang

Current behavior

I got type error while I write my custom navigateTo function.

function HomeScreen() {
  const navigation = useNavigation<StackNavigationProp<RootStackParamList>>();

  function navigateTo(
    screen: keyof RootStackParamList,
    params?: RootStackParamList[keyof RootStackParamList],
  ) {
    navigation.navigate(screen, params);
  }

  return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
      <Text>Home Screen</Text>
    </View>
  );
}

image

import React from 'react';
import {Text, View} from 'react-native';
import {
  createStackNavigator,
  StackNavigationProp,
} from '@react-navigation/stack';
import {
  NavigationContainer,
  RouteProp,
  useNavigation,
  useRoute,
} from '@react-navigation/native';

function HomeScreen() {
  const navigation = useNavigation<StackNavigationProp<RootStackParamList>>();

  function navigateTo(
    screen: keyof RootStackParamList,
    params?: RootStackParamList[keyof RootStackParamList],
  ) {
    navigation.navigate(screen, params);
  }

  return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
      <Text>Home Screen</Text>
    </View>
  );
}

function DetailsScreen() {
  const route = useRoute<RouteProp<RootStackParamList, 'Details'>>();
  return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
      <Text>Details Screen {route?.params?.userId}</Text>
    </View>
  );
}

type RootStackParamList = {
  Home: undefined;
  Details: {userId: string};
};

const Stack = createStackNavigator<RootStackParamList>();

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

Expected behavior

Should not have type error because with v5 the type is correct.

Reproduction

https://github.com/thormengkheang/TestRN

Platform

  • Android
  • iOS
  • Web
  • Windows
  • MacOS

Packages

  • @react-navigation/​bottom-tabs
  • @react-navigation/​drawer
  • @react-navigation/​material-bottom-tabs
  • @react-navigation/​material-top-tabs
  • @react-navigation/​stack
  • @react-navigation/​native-stack
  • react-native-tab-view
  • flipper-plugin-react-navigation

Environment

  • [] I've removed the packages that I don't use
package version
@react-navigation/native ^6.0.14
@react-navigation/stack ^6.3.5
react-native-safe-area-context ^3.4.1
react-native-screens ^3.1.0
react-native 0.69.5
yarn 1.22.19

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions