I have an object with many boolean fields like so:
type SomeObject = {
A: boolean
B: boolean
C: boolean
....
}
Is there an easy/efficient way to check if the OR
of all other fields (besides a specified field) are false
?
We can do it the brute-force way by just checking each field manually:
let foo:SomeObject = {
A: false
B: false
C: false
}
let isA = !(foo.B || foo.C)
let isB = !(foo.A || foo.C)
let isC = !(foo.A || foo.B)
But I'm sure there is a more elegant way of accomplishing this.
If you only need compile-time checking, it is very easy to do with a mapped type and an intersection (an identity mapped type thrown in for "prettifying" the generated type):
If you need compile-time type guarding so as the type can be narrowed later, then you need to use a union. The previous type can become a stepping stone for another utility type:
If you need runtime checks on top, there are options. Below is both a type and runtime guard based on the previous helper mapped types (
PossibleOnlyTrue
andOnlyOneTrue
):Playground