简体   繁体   English

根据其他接口的属性创建接口

[英]Create interface based on properties of other interfaces

I have two interfaces, Workflow and WorkflowVersion 我有两个接口, WorkflowWorkflowVersion

workflow.model.ts workflow.model.ts

import { WorkflowVersion } from './workflow-version.model';

export interface Workflow{
    name: string;
    ID: number;
    workflowVersions: WorkflowVersion[];
}

workflow-version.model.ts 工作流version.model.ts

export interface WorkflowVersion{
    versionID: number;
    lastPublished: string;
    environmentID: number;
}

I'd like to create an interface that 'flattens' the two. 我想创建一个“拉平”两者的界面。 This new interface, WorkflowFlat , should contain all non-object type properties of both interfaces. 这个新接口WorkflowFlat应该包含两个接口的所有非对象类型属性。 Currently I have this: 目前我有这个:

workflow-flat.model.ts 工作流flat.model.ts

export interface WorkflowFlat {
    name: string;
    ID: number;
    versionID: number;
    lastPublished: string;
    environmentID: number;
}

The model above achieves this, but it feels repetitive. 上面的模型可以达到这个目的,但是感觉很重复。 If I want to add a description property to WorkflowVersion down the road, I'd have to remember to also add it to WorkflowFlat . 如果我想在以后向WorkflowVersion添加description属性,则必须记住也将其添加到WorkflowFlat Is there any way to make the model automatically take all properties from the two interfaces and then create a new interface with the non-object ones? 有什么方法可以使模型自动从两个接口中获取所有属性,然后使用非对象接口创建一个新接口?

Aaron Beall's answer is close (sorry I can't comment yet), but it doesn't properly remove all the keys that extends object , so they'll be required by the final type as key: never which is not wanted. 亚伦·比尔(Aaron Beall)的答案很接近(对不起,我无法发表评论),但是它没有正确删除扩展object所有键,因此最终类型将需要它们作为key: never不需要。

The following snippet achieves the objective by reusing a type-level helper from the awesome tycho01/typical repo : 以下代码段通过重用tycho01 / typical repo中的类型级帮助程序来实现此目标:

export type NonMatchingPropNames<T, X> = { [K in keyof T]: T[K] extends X ? never : K }[keyof T];

export type NonMatchingProps<T, X> = Pick<T, NonMatchingPropNames<T, X>>;

type PrimitiveValuesOf<T> = NonMatchingProps<T, object>;

type A = PrimitiveValuesOf<Workflow & WorkflowVersion>;

const a: A = {
  name: '',
  ID: 0,
  versionID: 1,
  lastPublished: '',
  environmentID: 2
}; // OK

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

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