TC949: AnyOf
About 1 minTC-Medium
AnyOf
Problem
Implement Python's any function in the type system. The type takes an Array and returns true if any element of the Array is truthy. If the Array is empty, return false.
type Sample1 = AnyOf<[1, "", false, [], {}]> // expected to be true
type Sample2 = AnyOf<[0, "", false, [], {}]> // expected to be falseSolution
type Falsy = 0 | "" | false | [] | { [key: string]: never } | null | undefined
type AnyOf<T extends readonly any[]> = T[number] extends Falsy ? false : trueDeep Dive
Understanding Falsy Values in TypeScript
In JavaScript, the following values are considered falsy:
0""(empty string)false[](empty array — note: in JS this is truthy, but the challenge treats it as falsy){}(empty object — same as above)nullundefined
The challenge extends JavaScript's falsy definition to include empty arrays and empty objects.
Solution Breakdown
Define Falsy type: We create a union of all falsy types
{ [key: string]: never }represents an empty object — an object with no properties
Use
T[number]: This creates a union of all element types in the tupleConditional check:
T[number] extends Falsychecks if ALL elements are falsy- If every element extends
Falsy, returnfalse - Otherwise, return
true
- If every element extends
Alternative Approach: Recursive Solution
type Falsy = 0 | "" | false | [] | { [key: string]: never } | null | undefined
type AnyOf<T extends readonly any[]> = T extends [infer First, ...infer Rest]
? First extends Falsy
? AnyOf<Rest>
: true
: falseThis recursively checks each element. If we find a truthy element, return true immediately.
Edge Case: Empty Object Detection
The tricky part is detecting empty objects. { [key: string]: never } works because:
- It describes an object where every string key maps to
never - Since
neverhas no values, no keys can exist - Therefore, only
{}satisfies this constraint
Key Takeaways
- Indexed access
T[number]distributes tuple types into a union extendswith unions checks if ALL members of the left side extend the right side- Empty object detection uses
{ [key: string]: never }pattern - The challenge redefines falsy to include
[]and{}, unlike JavaScript
