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