[英]How can I make a generic TypeScript interface extend from another generic interface?
我有一個界面,有幾個元素:
export interface Item {
id: string;
code: string;
createdAt: string;
updatedAt: string;
level: number;
seq: number;
hasChildren: boolean;
parentObject?: Item;
children?: Item[];
}
我想要像Partial<T>
這樣的東西,我在這里有所幫助 : 在Typescript接口中使所有屬性都可選
但是,我想強制要求其中一個字段。 我實現了這個:
export interface ItemUpdate extends Partial<Item> {
id: string;
}
編得好。 但是,我想避免為每個接口聲明它。 為此,我使它更通用:
export interface UpdateOf<T> extends Partial<T> {
id: string; // the ID is the only mandatory value for an update
}
但是,這不再編譯,返回以下錯誤:
error TS2312: An interface may only extend a class or another interface.
我正在運行Angular 6.1.5,它附帶了Typescript 2.9(據我所知)。
錯誤消息已過期; 有一個未解決的問題需要更新。 當前規則是類或接口只能擴展對象類型或對象類型與靜態已知成員的交集,因為編譯器需要檢查在類或接口中聲明的屬性類型是否與對應的類型兼容基類型的屬性(如果有)。 Partial<Item>
的成員是靜態已知的,而Partial<T>
的成員則不是。 解決方法是使用交集類型而不是子接口:
export type UpdateOf<T> = Partial<T> & {id: string};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.