0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Beautiful! Exactly what I was after. Thank you!
Just one thing, I get a TS warning for "T": Type 'T' does not satisfy the constraint 'keyof SearchStackParamList'. Type 'string' is not assignable to type 'keyof SearchStackParamList'. So just replacing string with keyof SearchStackParamList is probably necessary?
If extends string is too broad, you can use 'SearchScreen' | 'Restaurant' or whatever is appropriate. - so use T extends keyof SearchStackParamList instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.