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

前端 未结 6 1778
梦谈多话
梦谈多话 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条回答
  •  萌比男神i
    2020-12-02 18:35

    Thanks @ryan-cavanaugh that put me in the right direction.

    I have a similar case, but then with array types. Struggled a bit with the syntax, so I put it here for later reference:

    interface BaseRule {
      optionalProp?: number
    }
    
    interface RuleA extends BaseRule {
      requiredPropA: string
    }
    
    interface RuleB extends BaseRule {
      requiredPropB: string
    }
    
    type SpecialRules = Array
    
    // or
    
    type SpecialRules = (RuleA | RuleB)[]
    
    // or (in the strict linted project I'm in):
    
    type SpecialRule = RuleA | RuleB
    type SpecialRules = SpecialRule[]
    

    Update:

    Note that later on, you might still get warnings as you use the declared variable in your code. You can then use the (variable as type) syntax. Example:

    const myRules: SpecialRules = [
      {
        optionalProp: 123,
        requiredPropA: 'This object is of type RuleA'
      },
      {
        requiredPropB: 'This object is of type RuleB'
      }
    ]
    
    myRules.map((rule) => {
      if ((rule as RuleA).requiredPropA) {
        // do stuff
      } else {
        // do other stuff
      }
    })
    

提交回复
热议问题