5

I am trying to extract the params as follows using useRoute as follows.

  const route = useRoute();
  const { params } = route;
  const {
   id, name,
  } = params;

Everything works fine but the linter is highlighting id and namewith the following error.

Property 'id' does not exist on type 'object | undefined

How do I overcome this issue.

Muljayan
  • 3,588
  • 10
  • 30
  • 54

1 Answers1

7

react-navigation exports a couple utility types to make your life easier when using hooks and defining props for your own components. They depend on you first defining types for your navigators.


Lets say you have a stack with two screens, A and B. First define what params each of those takes:

type StackParamsList = {
  A: undefined;
  B: {
    id: string;
    name: string;
  };
}

For typing useRoute in your screen B:

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

const route = useRoute<RouteProp<StackParamsList, 'B'>>();

route.params.id // OK
route.params.foo // error

Check the Type checking with Typescript article in react-navigation docs for more details and examples of typing other elements of your navigation stack.

Marek Lisik
  • 2,003
  • 1
  • 8
  • 17