Trung BìnhReact Native iconReact Native

`useNavigation` / `useRoute` — typing với TypeScript ra sao?

react-navigation v7 cung cấp generic types để type-safe navigation prop và route params.

Khai báo param list:

ts
type RootStackParamList = {
  Home: undefined
  Detail: { productId: string; from?: 'home' | 'search' }
  Profile: { userId: number }
}

Trong screen component:

tsx
import type { NativeStackScreenProps } from '@react-navigation/native-stack'

type Props = NativeStackScreenProps<RootStackParamList, 'Detail'>
function DetailScreen({ route, navigation }: Props) {
  const { productId, from } = route.params // typed
  navigation.navigate('Profile', { userId: 42 }) // typed
}

Tip 2026: declare global type-safe navigation bằng module augmentation:

ts
declare global {
  namespace ReactNavigation {
    interface RootParamList extends RootStackParamList {}
  }
}

Khi đó useNavigation() không cần generic — TypeScript tự suy luận.

Xem toàn bộ React Native cùng filter theo level & chủ đề con.

Mở danh sách React Native