TypeScript 如何提取仅存在于接口A不存在于接口B的属性构建新接口
解决方案
你可以通过TypeScript内置工具类型的组合实现需求,无需手动声明属性:
- 定义通用的差集属性计算类型,两种等价写法任选即可:
// 写法1:Exclude + Pick 组合 type ExclusiveProperties<A, B> = Pick<A, Exclude<keyof A, keyof B>> // 写法2:直接用Omit,更简洁 type ExclusiveProperties<A, B> = Omit<A, keyof B>
逻辑说明:先筛选出所有存在于A的键、但不存在于B的键的集合,再从A中提取这些键对应的属性,最终得到仅包含A独有属性的类型。
- 代入你的示例代码使用:
interface A { name: string; age: number; id: string; version: number; } interface B { name: string; age: number; } // 自动生成仅包含A独有属性的类型,等价于 { id: string; version: number } type PropertiesThatArePresentInAButNotInB = ExclusiveProperties<A, B> // 适配到你的mapper接口 interface IEntityFormStateMapper< E extends Entity<A>, FS extends B, OP extends PropertiesThatArePresentInAButNotInB > { toEntity: (formState: FS, omittedEntityProps: OP) => Result<Error, E>; toFormState: (entity?: E) => Result<Error, [FS, OP]>; }
如果需要编写通用的不绑定固定接口的mapper,也可以直接把实体、表单类型作为泛型传入,无需单独声明差集类型:
interface IUniversalEntityFormStateMapper<EntityType, FormStateType> { toEntity: ( formState: FormStateType, omittedEntityProps: Omit<EntityType, keyof FormStateType> ) => Result<Error, EntityType>; toFormState: ( entity?: EntityType ) => Result<Error, [FormStateType, Omit<EntityType, keyof FormStateType>]>; }
内容的提问来源于stack exchange,提问作者florian norbert bepunkt
相关产品推荐
相关产品推荐

