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

在TypeScript映射类型中添加嵌套对象的实现方案

TypeScript类型重构方案

核心思路

把原品种层级的sorting、allSelected、view属性统一迁移到对应动物大类(dog/cat)下的ui嵌套对象中,同时通过泛型约束让sorting类型与大类严格绑定。

分步实现

  1. 定义大类专属的排序扩展类型
    先为不同动物大类定义各自的排序规则,确保类型匹配:
// 狗类专属排序类型
type DogSorting = {
  sortBy: 'age' | 'weight' | 'breedPopularity';
  ascending: boolean;
};

// 猫类专属排序类型
type CatSorting = {
  sortBy: 'furLength' | 'playfulness' | 'indoorAdaptability';
  ascending: boolean;
};
  1. 抽离品种核心数据类型
    让每个品种仅保留核心业务数据items,剥离UI相关属性:
// 通用品种核心类型,泛型T对应具体品种的条目结构
type AnimalBreed<T> = {
  items: T[];
};
  1. 定义大类UI配置类型
    用泛型绑定对应的排序类型,统一管理大类下的UI状态:
// 通用大类UI配置,SortingType为传入的专属排序类型
type AnimalCategoryUI<SortingType> = {
  sorting: SortingType;
  allSelected: boolean;
  view: 'grid' | 'list' | 'card';
};
  1. 构建完整的大类与顶层类型
    结合上述类型,定义每个大类的完整结构,最后整合顶层类型:
// 狗品种的条目结构示例
type DogItem = {
  name: string;
  age: number;
  weight: number;
};

// 猫品种的条目结构示例
type CatItem = {
  name: string;
  furLength: 'short' | 'medium' | 'long';
  playfulness: 1 | 2 | 3 | 4 | 5;
};

// 狗大类完整类型
type DogCategory = {
  poodle: AnimalBreed<DogItem>;
  sausageDog: AnimalBreed<DogItem>;
  // 可添加更多狗品种...
  ui: AnimalCategoryUI<DogSorting>;
};

// 猫大类完整类型
type CatCategory = {
  persian: AnimalBreed<CatItem>;
  siamese: AnimalBreed<CatItem>;
  // 可添加更多猫品种...
  ui: AnimalCategoryUI<CatSorting>;
};

// 顶层动物类型
type Animals = {
  dog: DogCategory;
  cat: CatCategory;
};

效果验证

重构后的类型结构中,每个品种仅包含items,UI配置集中在大类的ui对象下,且dog.ui.sorting只能符合DogSorting类型,cat.ui.sorting只能符合CatSorting类型,完全满足需求。

内容的提问来源于stack exchange,提问作者four-eyes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:00:14