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 name
with the following error.
Property 'id' does not exist on type 'object | undefined
How do I overcome this issue.
With all these advantages and disadvantages, Typescript still provides great value to your project. You will save many hours of debugging time by using TypeScript. Therefore, you should definitely use TypeScript in your React Native Project.
While React Native is built in Flow, it supports both TypeScript and Flow by default.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With