2017-11-15 1 views
0

私は2つのインターフェースを持っています。バックエンドからワン:類似のオブジェクトをタイプスクリプトの同様のインターフェイスに準拠させてシームレスに別のオブジェクトに変換する方法はありますか?

interface IPrescriptionInfo { 
    budget?: BenefitBudget; 
    discount?: string; 
    prescriprionDate?: number; 
    prescriptionAPU?: string; 
    prescriptionAmount?: number; 
    prescriptionMedicine?: string; 
    prescriptionMethod?: string; 
    prescriptionMode?: PrescriptionMode; 
    prescriptionNumber?: string; 
    prescriptionRecordID?: string; 
    prescriptionRole?: string; 
    prescriptionSpeciality?: string; 
    prescriptionState?: PrescriptionStatus; 
    prescriptionType?: string; 
    prescriptionUserUID?: string; 
    protocolID?: string; 
    recipeEhrID?: string; 
} 

および内部データモデルのための別の1:シームレス「手動」プロパティを一つずつ割り当てず活字体の力を使ってIPrescriptionIPrescriptionInfoに準拠したオブジェクトを変換する方法

interface IPrescription { 
    budget?: string; 
    discount: number; 
    precriptionControl?: string; 
    prescriprionDate: Moment; 
    prescriptionAmount: number; 
    prescriptionAPU: string; 
    prescriptionMedicine: string; 
    prescriptionMethod: string; 
    prescriptionMode?: string; 
    prescriptionNumber: string; 
    prescriptionRecordID: string; 
    prescriptionRole: string; 
    prescriptionSpeciality: string; 
    prescriptionState?: string; 
    prescriptionType: string; 
    prescriptionUserUID: string; 
    protocolID: string; 
    recipeEhrID: string; 
} 


UPDATE
だけ明確にすること。

const prescription: IPrescription; 
const prescriptionInfo: IPrescriptionInfo; 
... 
prescription.discount = prescriptionInfo.discount; 
prescription.prescriprionDate = prescriptionInfo.prescriprionDate; 
prescription.prescriptionAPU = prescriptionInfo.prescriptionAPU; 
prescription.prescriptionAmount = prescriptionInfo.prescriptionAmount; 
... 
prescription.recipeEhrID = prescriptionInfo.recipeEhrID; 
+0

これらの異なるインターフェイスはなぜ始まっていますか?または、なぜ1つのインターフェースから継承しないのですか?いくつかの非互換性があるようです。 「予算」は異なるタイプです。 –

+0

理由のいくつかはJavaコードから生成されるということです。また、これらのクラス構造で何かを変更することはお勧めしません。理想的な解決策は、分離されたクラス構造であり、生成されたクラスで何かが変更されると、いくつかのアダプターが簡単に変更される可能性があります。 –

答えて

0

活字体が構造的に型付けされたタイプはすべて同じメンバーを持っている場合、あなたがそれらを直接割り当てることができますので、::のようにIMAはジュニア・スタイルのコードを回避する方法を探して

let info: IPrescriptionInfo; 

let prescription: IPrescription = info; 

のでは、あなたのあなたは2つの問題に直面します。 1つは、IPrescriptionInfoIPrescriptionよりも弱いタイプ(IPrescriptionInfoのメンバーはすべてオプションです。したがって、完全に空のオブジェクトである可能性があります)です。もう1つは、タイプ変換が必要なことです(たとえば、numberMoment)。

これは、単純にメンバをマッピングしているわけではありません(この回答の先頭にあるコードを使用できた場合)、ソースオブジェクト内の未定義のメンバーを処理する必要があること、値も。

prescription.prescriprionDate = (info.prescriprionDate) 
    ? new Moment(info.prescriprionDate) 
    : new Moment(0); 

あなたはおそらく空のオブジェクトよりも、あなたのソースオブジェクトをより堅牢にすることができた場合は、データをマッピングするためのコードを記述する必要性を減らすか、または削除することもできます。

関連する問題