Typescript Interface - Possible to make “one or the other” properties required?

前端 未结 6 1789
梦谈多话
梦谈多话 2020-12-02 18:06

Possibly an odd question, but i\'m curious if it\'s possible to make an interface where one property or the other is required.

So, for example...

int         


        
6条回答
  •  醉酒成梦
    2020-12-02 18:49

    Ok, so after while of trial and error and googling I found that the answer didn't work as expected for my use case. So in case someone else is having this same problem I thought I'd share how I got it working. My interface was such:

    export interface MainProps {
      prop1?: string;
      prop2?: string;
      prop3: string;
    }
    

    What I was looking for was a type definition that would say that we could have neither prop1 nor prop2 defined. We could have prop1 defined but not prop2. And finally have prop2 defined but not prop1. Here is what I found to be the solution.

    interface MainBase {
      prop3: string;
    }
    
    interface MainWithProp1 {
      prop1: string;
    }
    
    interface MainWithProp2 {
      prop2: string;
    }
    
    export type MainProps = MainBase | (MainBase & MainWithProp1) | (MainBase & MainWithProp2);
    

    This worked perfect, except one caveat was that when I tried to reference either prop1 or prop2 in another file I kept getting a property does not exist TS error. Here is how I was able to get around that:

    import {MainProps} from 'location/MainProps';
    
    const namedFunction = (props: MainProps) => {
        if('prop1' in props){
          doSomethingWith(props.prop1);
        } else if ('prop2' in props){
          doSomethingWith(props.prop2);
        } else {
          // neither prop1 nor prop2 are defined
        }
     }
    

    Just thought I'd share that, cause if I was running into that little bit of weirdness then someone else probably was too.

提交回复
热议问题