2

TLDR: Is it possible to annotate the useNavigation hook in a generic component?

If I create a <BackButton /> component that uses the useNavigation() hook is there a way to have it correctly type the hook when it is used in multiple screens?

The docs recommend typing this as:

const navigation = useNavigation<XScreenNavigationProp>();

However, this only works for when using useNavigation in a specific screen. How does one annotate the hook for more than one screen?

DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127
Justin.Mathew
  • 413
  • 5
  • 12

1 Answers1

3

You should specify a default type:

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

https://reactnavigation.org/docs/typescript/#specifying-default-types-for-usenavigation-link-ref-etc

Specifying a default type means you don't need to annotate it. This is perfect for generic components which are used in multiple places.

satya164
  • 9,464
  • 2
  • 31
  • 42
  • That's useful, thanks. It will still however be missing part of the type definition depending on navigation nesting and where the component is used but I imagine it would not be possible to fully type a generic component. – Justin.Mathew Feb 16 '22 at 20:05