tezvyn:

Type-safe navigation with TypeScript

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

typing navigation.

OUTLINE

define a ParamList mapping screen names to param types, type Screen via NativeStackScreenProps, and type useNavigation with the navigation prop generic so route names and params autocomplete.

WHAT THIS TESTS Whether you can wire React Navigation's generics so that screen names, params, and the navigation object are all statically typed, catching wrong route names or missing params at compile time.

A GOOD ANSWER COVERS Start by defining a ParamList type that maps each screen name to its params, using undefined for screens without params, for example Home: undefined and Post: { id: string }. Pass this ParamList to createNativeStackNavigator so the navigator's Screen names are checked. For each screen, type its props with NativeStackScreenProps so both route.params and the navigation prop are typed. To get a typed useNavigation in components that do not receive props, pass the navigation prop type, such as NativeStackNavigationProp of the ParamList, as the hook's generic, giving autocomplete for navigate names and enforcing the right param object. For convenience you can register a RootParamList by extending the global ReactNavigation namespace so the default useNavigation is typed app-wide without repeating the generic.

COMMON WRONG ANSWERS Casting navigation or route to any, which silences errors but removes all guarantees. Defining the ParamList but never passing it to the navigator or hooks, so nothing is actually checked. Using string literals for params with no shape type. Forgetting undefined for param-less screens, which forces callers to pass an empty object.

LIKELY FOLLOW-UPS How do you type nested navigators and composite navigation props? How does the global RootParamList registration differ from per-call generics? How do you type useRoute for a specific screen?

ONE CONCRETE EXAMPLE You declare type RootStackParamList = { Home: undefined; Post: { id: string } }. The navigator is createNativeStackNavigator with that generic. A reusable PostLink calls useNavigation typed as NativeStackNavigationProp of RootStackParamList; when it calls navigation.navigate('Post', { id }), TypeScript autocompletes 'Post' and errors if you forget id or pass a number. Misspelling 'Postt' or calling navigate('Home', {}) is rejected at compile time.

Read the original → reactnavigation.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.