如何使通用TypeScript接口从另一个通用接口扩展?

Dan*_*ray 10 typescript

我有一个界面,其中包含几个元素:

export interface Item {
  id: string;
  code: string;
  createdAt: string;
  updatedAt: string;
  level: number;
  seq: number;
  hasChildren: boolean;

  parentObject?: Item;
  children?: Item[];
}
Run Code Online (Sandbox Code Playgroud)

我想要类似的东西Partial<T>,我在这里很有帮助在Typescript界面​​中将所有属性设置为可选

但是,我想将其中一项设为必填项。我实现了这一点:

export interface ItemUpdate extends Partial<Item> {
  id: string;
}
Run Code Online (Sandbox Code Playgroud)

而且编译良好。但是,我想避免为每个接口都声明它。为此,我使它更通用:

export interface UpdateOf<T> extends Partial<T> {
  id: string; // the ID is the only mandatory value for an update
}
Run Code Online (Sandbox Code Playgroud)

但是,它不再编译,返回以下错误:

error TS2312: An interface may only extend a class or another interface.
Run Code Online (Sandbox Code Playgroud)

我正在运行Angular 6.1.5,它随Typescript 2.9一起提供(据我所知)。

Mat*_*hen 13

错误消息已过期;有一个开放的问题来更新它。当前的规则是类或接口只能扩展对象类型或对象类型与静态已知成员的交集,因为编译器需要检查在该类或接口中声明的属性的类型是否与相应的类型兼容基本类型的属性(如果有)。的成员Partial<Item>是静态已知的,而的成员Partial<T>则不是。一种解决方法是使用交集类型而不是子接口:

export type UpdateOf<T> = Partial<T> & {id: string};
Run Code Online (Sandbox Code Playgroud)