TypeScript如何复用现有interface仅修改单个属性的类型
方案1:使用内置Omit工具类型+交叉类型(最简洁)
直接用TypeScript官方提供的Omit剔除原接口的id属性,再交叉新的id类型定义即可:
type IListener = Omit<IInternalListener, 'id'> & { id: string | number }
Omit本质就是封装好的映射类型,会自动保留原接口除了指定属性之外的所有定义,不用自己手写遍历逻辑。
方案2:使用interface继承重写属性
如果更习惯用interface而不是type定义,也可以继承Omit处理后的类型,后续要新增额外属性也更方便:
interface IListener extends Omit<IInternalListener, 'id'> { id: string | number // 这里可以继续加IListener独有的其他属性 }
方案3:泛型基础接口(适合多变体场景)
如果后续还有更多id类型不同的变体接口,可以先定义泛型基础接口,不同场景直接传类型参数生成即可,扩展性最强:
// 定义泛型基础接口,默认id类型为string interface BaseListener<IdType = string> { element: HTMLElement, id: IdType, type: string, listener: EventListenerOrEventListenerObject, useCapture: boolean } // 直接生成两个所需接口 type IInternalListener = BaseListener type IListener = BaseListener<string | number>
方案4:自定义通用属性修改工具类型(适合频繁修改属性场景)
如果项目里经常需要修改单个属性生成新类型,可以自己封装一个通用的映射类型工具,后续所有类似场景都可以复用:
// 通用工具类型:修改T接口中K属性的类型为NewType type ModifyProperty<T, K extends keyof T, NewType> = { [P in keyof T]: P extends K ? NewType : T[P] } // 直接使用工具生成IListener type IListener = ModifyProperty<IInternalListener, 'id', string | number>
内容的提问来源于stack exchange,提问作者danday74
相关产品推荐
相关产品推荐

