简体   繁体   中英

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

I have the a class hierarchy like this:

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

I have to send data to an API, which will accept data where interfaceB have to contain only interfaceC when interfaceD is null and vice versa. Or it can contain both. The API is out of our hand to change.

Here are some examples:

When interfaceC is null (it needs to be the same way when interfaceD is null):

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

When both interfaceC and interfaceD both have values:

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

How to create the JSON from TyepScript so that it can be sent to the API? I'm very new to TypeScript.

You need to enable strictNullChecks in your TS-Config so that null and undefined are not part of your types by default. (Consider activating all strict checks.)

Then you could define interfaceB like this:

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;
};

This means that the data has to either contain property3 or property4 or both of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM