Avoid repetitive typescript definitions

Say I have these TS definitions:

export type SearchStackParamList = {
  SearchScreen: undefined;
  Restaurant: undefined;
};

export type SearchScreenProps = CompositeScreenProps<
  NativeStackScreenProps<SearchStackParamList, 'SearchScreen'>,
  CompositeScreenProps<
    NativeStackScreenProps<SearchStackParamList>,
    NativeStackScreenProps<RootStackParamList>
  >
>;

export type RestaurantScreenProps = CompositeScreenProps<
  NativeStackScreenProps<SearchStackParamList, 'Restaurant'>,
  CompositeScreenProps<
    NativeStackScreenProps<SearchStackParamList>,
    NativeStackScreenProps<RootStackParamList>
  >
>;

See how SearchScreenProps and RestaurantScreenProps are kinda redundant? Is there a way I can improve this so it’s less verbose? Maybe through some kind of "extend" function?

>Solution :

Make a wrapper type that takes a string type as a generic and gives the big complicated CompositeScreenProps in exchange.

type ScreenProps<T extends string> = CompositeScreenProps<
  NativeStackScreenProps<SearchStackParamList, T>,
  CompositeScreenProps<
    NativeStackScreenProps<SearchStackParamList>,
    NativeStackScreenProps<RootStackParamList>
  >
>;

export type SearchScreenProps = ScreenProps<'SearchScreen'>;
export type RestaurantScreenProps = ScreenProps<'Restaurant'>;

If extends string is too broad, you can use 'SearchScreen' | 'Restaurant' or whatever is appropriate.

Leave a Reply