Implement Python liked `any` function in the type system. A type takes the Array and returns `true` if any element of the Array is true. If the Array is empty, return `false`. Learn array type operations in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a Python-like AnyOf type that takes an array and returns true if any element is truthy, or false if the array is empty or all elements are falsy.
Implement Python liked any function in the type system. A type takes the Array and returns true if any element of the Array is true. If the Array is empty, return false.
For example:
type Sample1 = AnyOf<[1, "", false, [], {}]> // expected to be true.
type Sample2 = AnyOf<[0, "", false, [], {}]> // expected to be false.Change the following code to make the test cases pass (no type check errors).
type Falsy = 0 | '' | false | [] | { [key: string]: never } | undefined | null
type AnyOf<T extends readonly any[]> = T extends [infer First, ...infer Rest]
? First extends Falsy
? AnyOf<Rest>
: true
: falseHow it works:
Falsy defines a union of all types considered falsy: 0, '', false, [], empty object {} (represented as { [key: string]: never }), undefined, and nullT extends [infer First, ...infer Rest] recursively destructures the tuple, pulling off the first elementFirst extends Falsy checks whether the current element is a falsy typeAnyOf<Rest> to check remaining elementstruefalse since no truthy element was foundThis challenge helps you understand recursive tuple processing and falsy type checking, and how to apply these concepts in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount