You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免重复的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 08:40:49