I'm confused about how to explicitly type my Drawer Navigator in my TypeScript code.
I can easily get things to behave as I expect, for example, in the following code. In particular the drawer-specific methods (e.g., openDrawer
, etc.) all works as they should. But my linter complains that none of those methods are defined with
TS2339: Property 'openDrawer' does not exist on type 'NavigationProp { key: string; index: number; routeNames: never[]; history?: unknown[] | undefined; routes: NavigationRoute []; type: string; stale: false; }>, {}, {}>'.
I can move this problem around with tricks like replacing
const navigation = useNavigation()
with
const navigation: Drawer = useNavigation()
but always get some sort of error (here "TS2304: Cannot find name 'Drawer'."). And can eliminate the error by guessing
const navigation: Drawer.DrawerNavigationProp<any> = useNavigation()
But I've lost track of what is going on there.
What is the correct way to specify that navigation
is a navigation drawer (I'm not even sure of the correct type to specify)?
NavigationExample.tsx:
import React, { ReactElement } from 'react'import {useNavigation} from "@react-navigation/native"const NavigationExample = (): ReactElement => { const navigation = useNavigation() return (<View style={ styles.container }><Text style={ styles.testText }>Navigation</Text><Button onPress={ () => navigation.toggleDrawer() } title="Toggle" color="blue" /><Button onPress={ () => navigation.openDrawer() } title="Open" color="green" /><Button onPress={ () => navigation.closeDrawer() } title="Close" color="red" /></View> )}
App.tsx:
import NavigationExample from './components/NavigationExample'//...import { createDrawerNavigator } from '@react-navigation/drawer'import { NavigationContainer } from '@react-navigation/native'export const Drawer = createDrawerNavigator()const App = () => { return (<NavigationContainer><Drawer.Navigator><Drawer.Screen name="Navigation" component={ NavigationExample } /> // ...</Drawer.Navigator></NavigationContainer> )}export default App