Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading