避免重复的 typescript 定义

yqhsw0fo  于 2023-02-05  发布在  TypeScript
关注(0)|答案(1)|浏览(131)

假设我有这些TS定义:

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

看看SearchScreenPropsRestaurantScreenProps是如何有点冗余的?有没有什么方法可以改进它,使它不那么冗长?也许通过某种“扩展”函数?

e0bqpujr

e0bqpujr1#

创建一个 Package 器类型,该类型将字符串类型作为泛型,并给出大而复杂的CompositeScreenProps作为交换。

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

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

如果extends string太宽,可以使用'SearchScreen' | 'Restaurant'或任何合适的值。

相关问题