指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

有如下ts类型定义:

ListResponse.ts
原始写法:
export type RawSection = {
  value: number;
  label: string;
};
  
export type RawTicket = {
  id: number;
  title: string;
  section: RawSection;
};
  
export type RawAddonsEditResponse = {
  id: number;
  title: string;
  price: string;
  quantity: number;
  additionalInformation: string;
  tickets: RawTicket[];
}
  
export type Section = {
  id: number;
  title: string;
};
  
export type Ticket = {
  id: number;
  title: string;
  section: Section;
};
  
export type AddonsEditResponse = {
  id: number;
  title: string;
  price: string;
  quantity: number;
  additionalInformation: string;
  tickets: Ticket[];
};
  
优化后:
type BaseTicket<S> = {
  id: number;
  title: string;
  section: S;
};
  
type BaseAddonsEditResponse<T> = {
  id: number;
  title: string;
  price: string;
  quantity: number;
  additionalInformation: string;
  tickets: T[];
};
  
export type RawSection = {
  value: number;
  label: string;
};
  
export type RawTicket = BaseTicket<RawSection>;
  
export type RawAddonsEditResponse = BaseAddonsEditResponse<RawTicket>;
  
export type Section = {
  id: number;
  title: string;
};
  
export type Ticket = BaseTicket<Section>;
  
export type AddonsEditResponse = BaseAddonsEditResponse<Ticket>;

优化分析:

提取通用类型:将 BaseSection, BaseTicket, 和 BaseAddonsEditResponse 定义为通用类型,并通过泛型参数增强复用性。
复用性提升:通过泛型参数 S 和 T,将类型从依赖具体的 RawSection 或 Section,转变为可以适配不同上下文的通用类型。
最终类型定义清晰化:后面的三个最终类型 (Section, Ticket, AddonsEditResponse) 依然保留原样,保持清晰的业务含义。
这样可以减少重复代码,并使代码更具扩展性。如果需要新增类似的类型,维护起来也更简单。