React Navigation V5 + Typescript Error: Property 'fullName' does not exist on type 'object'

Viewed 2094

My Goal:

I'm trying to add Typescript typings, but having an issue with route.params.fullName. When I console.log(route.params), the object { fullName: 'John Smith' } is logged. Why is Typescript having an issue with fullName?

The weird part is that the code works and when I navigate to the screen, the header title is updated with route.params.fullName.

Error:

Property 'fullName' does not exist on type 'object'.

Functional Component:

  // React Hooks: React Navigation
  const route = useRoute();

  // React Hooks: Lifecycle Methods
  useEffect(() => {
    console.log(route.params);

    // React Navigation: Set Options
    props.navigation.setOptions({
      // ISSUE HERE
      title: route.params.fullName,
    });
  }, [props.navigation, route.params]);
4 Answers

Since you are using React Navigation V5, as it says in the documentation, you should first define your route stack params list:

export type RootStackParamList = {
  Home: undefined;
  SomeRouteName: { fullName: string };
  ...
};

Then while creating your stack navigator, you should use your param list type definition:

const Stack = createStackNavigator<RootStackParamList>();

Finally in your screen component:

import { RootStackParamList } from 'YOUR_ROUTE_STACK_PARAM_LIST_PATH';

type SomeScreenComponentRouteProp = RouteProp<RootStackParamList, 'SomeRouteName'>;

interface Props {
  route?: SomeScreenComponentRouteProp;
}

const SomeScreenComponent:  React.FC<Props> = (props) => {
  ...
}

This way Typescript will know which params are expected in your route props.

Now you can access your fullName parameter via props.route.params.fullName without having any errors or warnings.

using

let route: any = useRoute();

will solve the typescript problem.

Example:

Assuming you need to read a parameter named data from route params that you have passed through:

navigation.navigate("productDetails",{data: {title: "New Product Title"})

so in your productDetails page you can read it like this:

import {useRoute} from '@react-navigation/native';

let route: any = useRoute();
let data = route.params?.data ? route.params.data : {};

and now there is no typescript problems with your code anymore.

Also, you could

import { RootStackParamList } from 'YOUR_ROUTE_STACK_PARAM_LIST_PATH';

type Props =StackScreenProps<RootStackParamList, 'SomeRouteName'>;

const SomeScreenComponent:  React.FC<Props> = (props) => {
  ...
}

This way you take prop typing directly

@tsomone answer works but a better and quick solution rather than just using any and ignoring everything, is to define route type like this:

import {RouteProp, useRoute} from '@react-navigation/native';
...
let route: RouteProp<{params: {fullName: string}}, 'params'> = useRoute();

You will no longer get that error.

Related