如何复用TypeScript接口,避免重复定义不同类型属性?
TypeScript 接口复用方案:避免重复定义相似结构
方案一:泛型接口(推荐,灵活扩展性强)
通过泛型参数控制需要动态变化的属性类型,默认值设为string,一次性生成两种目标接口,无需重复编写公共属性。
// 泛型基础接口,T 控制 ownerType 和 agreeTermsCheckbox 的类型,默认值为 string interface BaseFormValuesState<T = string> { ownerType: T; platformUrl?: string; serviceUrl?: string; fullName: string; email: string; password1: string; password2: string; agreeTermsCheckbox: T; } // 所有属性均为 string 的接口(直接使用默认泛型) type FormValuesStateString = BaseFormValuesState; // ownerType 和 agreeTermsCheckbox 为 boolean 的接口 type FormValuesStateBoolean = BaseFormValuesState<boolean>;
验证示例数据:
// 适配 boolean 类型的接口 const dataBoolean: FormValuesStateBoolean = { ownerType: true, platformUrl: 'test', serviceUrl: 'test', fullName: 'test', email: 'test', password1: 'test', password2: 'test', agreeTermsCheckbox: false, }; // 适配 string 类型的接口 const dataString: FormValuesStateString = { ownerType: 'test now as string', platformUrl: 'test', serviceUrl: 'test', fullName: 'test', email: 'test', password1: 'test', password2: 'test', agreeTermsCheckbox: 'now as string', };
方案二:工具类型组合(Omit + 交叉类型)
先定义全string类型的基础接口,再通过Omit剔除需要修改的属性,结合交叉类型替换为目标类型。
// 基础接口(全 string 版本) interface BaseFormValuesState { ownerType: string; platformUrl?: string; serviceUrl?: string; fullName: string; email: string; password1: string; password2: string; agreeTermsCheckbox: string; } // 生成 boolean 变体接口:剔除原属性后交叉新类型 type FormValuesStateBoolean = Omit<BaseFormValuesState, 'ownerType' | 'agreeTermsCheckbox'> & { ownerType: boolean; agreeTermsCheckbox: boolean; }; // 原基础接口直接作为 string 版本使用 type FormValuesStateString = BaseFormValuesState;
方案对比
- 泛型方案:适合需要多种类型变体的场景,后续新增类型只需传入新的泛型参数即可,扩展性更强。
- 工具类型方案:逻辑直观,适合仅需两种固定变体的简单场景。
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

