簡體   English   中英

如何在 TypeScript 中的類型上定義互斥屬性?

[英]How to define mutually exclusive properties on a type in TypeScript?

我有這樣的 class 層次結構:

export interface interfaceA {
  property1: string;
  property2: interfaceB;
}
    
export interface interfaceB{
  property3: interfaceC;
  property4: interfaceD;
}
    
export interface interfaceC{
  property5: string;
}
    
export interface interfaceD{
  property6: string;
}

我必須將數據發送到 API,當interfaceD為 null 時,它將接受interfaceB必須僅包含interfaceC的數據,反之亦然。 或者它可以同時包含兩者。 API 無法更改。

這里有些例子:

當interfaceC為null時(interfaceD為null時也需要同理):

{
interfaceA :{
 property1: "somevalue",
 property2: {
  interfaceB:{
    property4: 
    {
      property6: "somevalue";
    }
   }
  }
 }
}

當 interfaceC 和 interfaceD 都具有值時:

{
interfaceA :{
 property1: "somevalue",
 property2: {
  interfaceB:{
    property3: 
    {
      property5: "somevalue";
    },
    property4: 
    {
      property6: "somevalue";
    }
   }
  }
 }
}

如何從 TyepScript 創建 JSON 以便可以將其發送到 API? 我對 TypeScript 很陌生。

您需要在 TS-Config 中啟用strictNullChecks ,以便nullundefined默認情況下不屬於您的類型。 (考慮激活所有嚴格檢查。)

然后你可以像這樣定義interfaceB

export type interfaceB = {
  property3: interfaceC;
  property4: interfaceD;
} | {
  property3: interfaceC;
  property4: null; // you might try to remove this line
} | {
  property3: null; // you might try to remove this line
  property4: interfaceD;
};

這意味着數據必須包含property3property4或兩者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM