最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Dynamic type for custom navigator in react native - Stack Overflow

programmeradmin0浏览0评论

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!

发布评论

评论列表(0)

  1. 暂无评论