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

TypeScript 如何提取仅存在于接口A不存在于接口B的属性构建新接口

解决方案

你可以通过TypeScript内置工具类型的组合实现需求,无需手动声明属性:

  1. 定义通用的差集属性计算类型,两种等价写法任选即可:
// 写法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独有属性的类型。

  1. 代入你的示例代码使用:
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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 20:06:01