打字稿:拆分一个大界面

时间:2020-08-27 09:39:51

标签: typescript interface

我创建了一个接口,用于接收来自HTTP请求的响应。服务的响应包含很多元素,因此我的界面很大。

接口

export interface LargeInterface {
    object_1: string;
    object_2: string;
    object_3: string;
    object_4: string;
    object_5: string;
    object_6: string;
    ...
    object_n: string;
}

致电

this.http.get<LargeInterface>( this.url, formData );

我想将接口拆分为多个部分,但是我需要get方法正确解析它。哪个方法不错?

我尝试了继承,但是我认为这不是一个好习惯,因为接口各部分之间的关​​系不是基于继承的。

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以将接口与&

结合使用
interface I1 {
  object_1: string
}

interface I2 {
  object_2: string
}

type LargeInterface = I1 & I2

答案 1 :(得分:0)

您可以创建子接口并将其组合为一个

interface Base_Data {
  object_1: string
}

interface Special_Data {
  object_2: string
}

interface LargeInterface extends Base_Data, Special_Data {
}

并按预期使用它们

this.http.get<LargeInterface>( this.url, formData );