navigator가 ID를 갖는다면 다음과 같이 할 수 있다
type Props = NativeStackScreenProps<RootStackParamList, 'Profile', 'MyStack'>;
이를 통해 navigate, push 등을 사용중인 route의 이름 및 params의 타입을 확인할 수 있다
route.params에서 params를 입력하고 setParams를 호출할 때 params를 입력하려면 현재 경로의 이름이 필요
마찬가지로 @react-navigation/stack용 StackScreenProps, @react-navigation/drawer의 DrawerScreenProps, @react-navigation/bottom-tabs 등을 가져올 수 있다
그런 다음 위에서 정의한 Props type을 사용하여 component에 annotate를 달 수 있다
function ProfileScreen({ route, navigation }: Props) {
// ...
}
다음과 같이 Props type에서 navigation과 route의 type을 가져올 수 있다
type ProfileScreenNavigationProp = Props['navigation'];
type ProfileScreenRouteProp = Props['route'];
또는 navigation과 route에 별도로 annotate를 달 수 있다
navigation의 prop type을 가져오려면 navigator에서 해당 타입을 가져와야 한다
만약 @react-navigation/native-stack 용 NativeStackNavigationProp을 가져온다면
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
type ProfileScreenNavigationProp = NativeStackNavigationProp<RootStackParamList, 'Profile'>;
마찬가지로
@react-navigation/stack에서 StackNavigationProp,
@react-navigation/drawer에서 DrowerNavigationProp,
@react-navigation/bottom-tabs에서 BottomTabNavigationProp 등 가져올 수 있다
route prop의 type을 가져오려면 @react-navigation/native의 RouteProp type을 사용해야 한다
import type { RouteProp } from '@react-navigation/native';
type ProfileScreenRouteProp = RouteProp<RootStackParamList, 'Profile'>
별도의 types.tsx
파일을 생성하여 한 곳에서 관리, 코드 재사용을 하는 것이 좋다