admin管理员组

文章数量:1410706

In my React Native app I have a custom Navigator file in which I have multiple navigation methods because are used from multiple places in the app.

I have a big issue at the moment because I have some castings to any and I am trying to avoid that.

I have 2 types of methods but I want to reduce them to just one.

navigateToY(navigation: NavigationProps['navigation']) {
     navigation.navigate('Y');
}

navigateToX(component: React.Component<NavigationProps, {}> | NavigationProp<any>) {
    const navigation = (component as any)?.props?.navigation ?? component;
    navigation.navigate('X');
}

Also the navigation param will always be of type StackNavigationProp but with different Param List and screen

In my case I would like to get rid of any and use my custom NavigationProps which is this one:

export interface NavigationProps {
  navigation?: any;
  route?: any;
}

Also this one has any because my navigate functions can be called from different Stacks with different param list.

Here is my param list:

export type TabsParamList = {
  ATab: NavigatorScreenParams<AParamList>;
  BTab: NavigatorScreenParams<BParamList>;
  CTab: NavigatorScreenParams<CParamList>;
  DTab: NavigatorScreenParams<DParamList>;
};

export type MainParamList = {
  1Page: {};
  2Page: {};
  MainTabs: NavigatorScreenParams<TabsParamList>;
  3Page: {};
  4Page: {};
}

As you can see, my param lists are a lil bit nested, but what I am trying to achieve is to create some kind of dynamic/generic type for my NavigationProps that would work with each Param list I would send. Also, for each call I know what Param List is used so I can directly specify the expected Param List, but couldn't yet figure a way to do it.

How should I handle this case to avoid the any and actually use the types that I need?

Thank you!

本文标签: typescriptDynamic type for custom navigator in react nativeStack Overflow