Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Better way of defining types for 'navigation' object, when using Stack Navigator in React Native

$
0
0

I'm having some trouble with modularization for the prop types, when using react-navigation.

My problem is:The React Navigation doc Typescript section suggests creating the types for each screen props like so:

//types.tsexport type RootStackParamList = {  Home: undefined;  Profile: { userId: string };  Feed: { sort: 'latest' | 'top' } | undefined;};// Profile.tsximport type { NativeStackScreenProps } from '@react-navigation/native-stack';import type { RootStackParamList } from  './types';type ProfileProps = NativeStackScreenProps<RootStackParamList, 'Profile'>;

So, basically, importing the NativeStackScreenProps type, and passing both the RootStackParamList, and the page name, as a string.

But if I had to define prop types for another page in the same Stack, e.g. the Home page, I would have to repeat the SAME two type imports, which is not ideal, as far as I know.

All that changes is the string ('Profile', 'Home', etc) passed into the type.

// Home.tsximport type { NativeStackScreenProps } from '@react-navigation/native-stack';import type { RootStackParamList } from './types';type HomeProps = NativeStackScreenProps<RootStackParamList, 'Home'>;

I'm kind of a beginner with TS, so my question is: How can I create a generic type that could help me avoid using the same two imports on every page? Since the only thing changing between these two prop types is a string.


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>