如何避免重复的TypeScript屏幕Props类型定义?
优化TypeScript冗余Props定义的方案
当然可以通过提取公共类型+泛型的方式简化这些定义,核心思路是把重复的结构抽成可复用的基础类型,再通过泛型适配不同的屏幕名称:
步骤1:提取公共外层Props
先把两个屏幕Props中重复的嵌套CompositeScreenProps部分抽成单独类型:
// 提取Search栈共享的外层Props结构 type SearchStackOuterProps = CompositeScreenProps< NativeStackScreenProps<SearchStackParamList>, NativeStackScreenProps<RootStackParamList> >;
步骤2:创建通用屏幕Props类型
定义一个接受屏幕名称作为泛型参数的通用类型,把可变的屏幕名称部分用泛型占位:
// 通用的Search栈屏幕Props类型,支持传入具体屏幕名称 type SearchStackScreenProps<ScreenName extends keyof SearchStackParamList> = CompositeScreenProps< NativeStackScreenProps<SearchStackParamList, ScreenName>, SearchStackOuterProps >;
步骤3:简化具体屏幕Props定义
现在只需一行代码就能定义每个屏幕的Props,完全复用通用类型:
export type SearchScreenProps = SearchStackScreenProps<'SearchScreen'>; export type RestaurantScreenProps = SearchStackScreenProps<'Restaurant'>;
这种方式既消除了冗余代码,也提升了可维护性——后续如果SearchStackParamList新增屏幕,直接复用SearchStackScreenProps传入新的屏幕名称即可,无需重复编写嵌套的CompositeScreenProps结构。
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

