I have the following types:
type OrBranch = {
or: Node[]
}
type AndBranch = {
and: Node[]
}
I’d like a type Branch
that can be either an OrBranch
or an AndBranch
. So I first tried:
type Branch = AndBrand | OrBranch
Work great, unless I want to do something like:
let branch: Branch = ...
let andOr = 'and'; // or 'or'
let nodes = branch[andOr]
Then I get that branch
isn’t indexable. OK, so I try an indexable type:
type AndOr = 'and' | 'or';
type Branch = Record<AndOr, Node[]>;
But that requires that BOTH and
and or
exist, so I can’t cast and AndBranch to Branch in this case.
Similarly
type Branch = Record<AndOr, Node[]> | AndBranch | OrBranch
doesn’t work, for the same reason.
I know there’s a way to require exactly one of and
and or
(like the answer to Enforce Typescript object has exactly one key from a set). But that type is not indexable.
Is it possible to get both effects?