打字稿中现有类型的匿名扩展

时间:2019-06-03 13:22:06

标签: typescript typescript-typings

我正在编写现有API的某些类型的结构。

export interface Filter {
 value: number;
 operator: string;
};

export interface MySetup {
  foo: Filter;
  bar: {
   value: number;
   operator: string;
   additionWithName: string;
  };
  alice: {
   value: number;
   operator: string;
   additionWithOtherName: string;
  };
}

我也可以这样写:

export interface Filter {
 value: number;
 operator: string;
};
export interface FilterBar extends Filter {
  additionWithName: string;
};
export interface FilterAlice extends Filter {
  additionWithOtherName: string;
};

export interface MySetup {
  foo: Filter;
  bar: FilterBar;
  alice: FilterAlice;
}

是否可以以匿名方式扩展某些接口?我想写这样的东西:

export interface Filter {
 value: number;
 operator: string;
};

export interface MySetup {
  foo: Filter;
  bar: Filter extends {additionWithOtherName: string;};
  alice: Filter extends {additionWithName: string;};
}

1 个答案:

答案 0 :(得分:1)

您不能进行内联扩展,但是intersection type将提供一个很好的近似值,即。必须具有接口属性和其他一些额外属性的类型:

export interface Filter {
 value: number;
 operator: string;
};

export interface MySetup {
  foo: Filter;
  bar: Filter & {additionWithOtherName: string;};
  alice: Filter & {additionWithName: string;};
}