Issue
Say I have a list of booleans:
const a: boolean[] = [true, false, false];
Can I build a type conditional that fires only when at least one of the booleans is true?
I can do it for the case where they're all true:
type BList = true[] | false[];
type AreAllTrue<T extends BList> = T[number] extends true ? true : false;
const a: BList = [true, true, true];
const b: AreAllTrue<typeof a> = true; // This compiles
const c: AreAllTrue<typeof a> = false; // This doesn't (as expected)
// type AnyAreTrue<???> = ???
But I need the list to have both true and false, not just a list full of one type of boolean.
Solution
Perhaps this is what you want?
type AnyIsTrue<T extends boolean[]> = T extends false[] ? false : true
type _test0 = AnyIsTrue<[]> // false
type _test1 = AnyIsTrue<[false]> // false
type _test2 = AnyIsTrue<[false, true]> // true
type _test3 = AnyIsTrue<[false, true, false]> // true
Hopefully this makes sense: an array of booleans doesn't have any trues if and only if it's a subtype of false[].
However, as I said in the comment, if the type of your variable is boolean[], TypeScript can't say much about it. It doesn't know what values are in the array.
type _test4 = AnyIsTrue<boolean[]> // true
Answered By - decorator-factory
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.