简体   繁体   English

打字稿:获取由接口 A 中存在但不在接口 B 中的属性组成的接口

[英]Typescript: Get interface that consist of properties that are present in interface A, but not in interface B

I'm writing a mapper to translate between a serialized entity state and a form state.我正在编写一个映射器来在序列化实体状态和表单状态之间进行转换。

Given two interfaces A and B: How can I get a third interface C that contains the properties that are present in A but missing in B?给定两个接口 A 和 B:如何获得第三个接口 C,其中包含 A 中存在但 B 中缺失的属性?

interface A {
    name: string;
    age: number;
    id: string;
    version: number;
}

// could be written interface B extends Omit<A, "version" | "id"> {}
interface B {
    name: string;
    age: number;
}

interface PropertiesThatArePresentInAButNotInB {
    // ???
}

// this is my mapper interface (just for illustrating the use case)
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]>;
}

What you want to do is as simple as Omit<A, keyof B> .您想要做的就像Omit<A, keyof B>一样简单。

You can give this an alias like type PropertiesOfAButNotB = Omit<A, keyof B> if you are going to use it in multiple places.如果您打算在多个地方使用它,您可以给它一个别名,如type PropertiesOfAButNotB = Omit<A, keyof B>

没关系,在这里找到了一个实现(差异): https : //github.com/piotrwitek/utility-types

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM