Skip to content

Commit ddfbe48

Browse files
committed
Improve typescript docs
1 parent 26c42f0 commit ddfbe48

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

versioned_docs/version-5.x/typescript.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,53 @@ type Props = {
8787

8888
This allows us to type check the route object, such as `route.params`.
8989

90+
To summarize:
91+
92+
```tsx
93+
import { RouteProp } from '@react-navigation/native';
94+
import { StackNavigationProp } from '@react-navigation/stack';
95+
96+
type RootStackParamList = {
97+
Home: undefined;
98+
Profile: { userId: string };
99+
Feed: { sort: 'latest' | 'top' } | undefined;
100+
};
101+
102+
type ProfileScreenRouteProp = RouteProp<RootStackParamList, 'Profile'>;
103+
104+
type ProfileScreenNavigationProp = StackNavigationProp<
105+
RootStackParamList,
106+
'Profile'
107+
>;
108+
109+
type Props = {
110+
route: ProfileScreenRouteProp;
111+
navigation: ProfileScreenNavigationProp;
112+
};
113+
```
114+
115+
Then you can use the `Props` type to annotate your component.
116+
117+
For function components:
118+
119+
```tsx
120+
function ProfileScreen({ route, navigation }: Props) {
121+
// ...
122+
}
123+
```
124+
125+
For class components:
126+
127+
```ts
128+
class ProfileScreen extends React.Component<Props> {
129+
render() {
130+
// ...
131+
}
132+
}
133+
```
134+
135+
We recommend creating a separate `types.tsx` file where you keep the types and import them in your component files instead of repeating them in each file.
136+
90137
### Nesting navigators
91138

92139
When we nest navigators, the navigation prop of the screen is a combination of multiple navigation props. For example, if we have a tab inside a stack, the `navigation` prop will have both `jumpTo` (from the tab navigator) and `push` (from the stack navigator). To make it easier to combine types from multiple navigator, you can use the `CompositeNavigationProp` type:

0 commit comments

Comments
 (0)