简体   繁体   English

如何在 TypeScript 中的类型上定义互斥属性?

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

I have the a class hierarchy like this:我有这样的 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;
}

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.我必须将数据发送到 API,当interfaceD为 null 时,它将接受interfaceB必须仅包含interfaceC的数据,反之亦然。 Or it can contain both.或者它可以同时包含两者。 The API is out of our hand to change. API 无法更改。

Here are some examples:这里有些例子:

When interfaceC is null (it needs to be the same way when interfaceD is null):当interfaceC为null时(interfaceD为null时也需要同理):

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

When both interfaceC and interfaceD both have values:当 interfaceC 和 interfaceD 都具有值时:

{
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?如何从 TyepScript 创建 JSON 以便可以将其发送到 API? I'm very new to TypeScript.我对 TypeScript 很陌生。

You need to enable strictNullChecks in your TS-Config so that null and undefined are not part of your types by default.您需要在 TS-Config 中启用strictNullChecks ,以便nullundefined默认情况下不属于您的类型。 (Consider activating all strict checks.) (考虑激活所有严格检查。)

Then you could define interfaceB like this:然后你可以像这样定义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;
};

This means that the data has to either contain property3 or property4 or both of them.这意味着数据必须包含property3property4或两者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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