我是 TypeScript 和 Angular 的新手。
所以我目前有一個模型
export interface ActionBE {
type: string;
actionInfo: ActionInfoBE;
}
export interface ActionInfoBE {
field_id: string;
value: string;
}
現在,我需要實作多種型別的操作,其中 ActionInfo 將具有不同的結構。這在 Java 中使用父類很容易做到,然后當我們序列化為 JSON 時,Jackson 只是正確地序列化它。
現在我想要的是
export interface ActionBE {
type: string;
actionInfo: ActionInfoBE; --------> This model could be either of below 2 based on `type` above.
}
export interface SetObjectValueActionInfoBE {
field_id: string;
value: string;
}
export interface SendEmailActionInfoBE {
recipient_email_address: string;
message: string;
}
uj5u.com熱心網友回復:
如果您想驗證多種型別,可以使用 OR 運算子“|”
export interface ActionBE {
type: string;
actionInfo: ActionInfoBE | SetObjectValueActionInfoBE | SendEmailActionInfoBE; --------> This could check one of the above and satisfies the type
}
export interface SetObjectValueActionInfoBE {
field_id: string;
value: string;
}
export interface SendEmailActionInfoBE {
recipient_email_address: string;
message: string;
}
uj5u.com熱心網友回復:
你可以使用泛型:
export interface ActionBE<T = any> {
type: string;
actionInfo: T;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/339811.html
