navigatior检测
要对路由和参数进行验证,首先要创建一个类型对象
type RootStackParamList = {
Profile: { userId: string };
};
同样的其他路由也需要定义
type RootStackParamList = {
Home: undefined;
Profile: { userId: string };
Feed: { sort: 'latest' | 'top' } | undefined;
};
undefined表示该路有没有参数,联合的参数表示参数是可选的
screens检测
在screens进行类型检测,我们需要同时对navigation porp和route prop进行注释
import { RouteProp } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
type RootStackParamList = {
Home: undefined;
Profile: { userId: string };
Feed: { sort: 'latest' | 'top' } | undefined;
};
type ProfileScreenRouteProp = RouteProp<RootStackParamList, 'Profile'>;
type ProfileScreenNavigationProp = StackNavigationProp<
RootStackParamList,
'Profile'
>;
type Props = {
route: ProfileScreenRouteProp;
navigation: ProfileScreenNavigationProp;
};
然后你在页面中可以这样去使用
useRoute<ProfileScreenRouteProp>().params;
useNavigation<ProfileScreenNavigationProp>();
通过以上的步骤就可以对路由参数类型进行限制了