|
| 1 | +/* |
| 2 | + 949 - AnyOf |
| 3 | + ------- |
| 4 | + by null (@kynefuk) #medium #array |
| 5 | +
|
| 6 | + ### Question |
| 7 | +
|
| 8 | + 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`. |
| 9 | +
|
| 10 | + For example: |
| 11 | +
|
| 12 | + ```ts |
| 13 | + type Sample1 = AnyOf<[1, '', false, [], {}]> // expected to be true. |
| 14 | + type Sample2 = AnyOf<[0, '', false, [], {}]> // expected to be false. |
| 15 | + ``` |
| 16 | +
|
| 17 | + > View on GitHub: https://tsch.js.org/949 |
| 18 | +*/ |
| 19 | + |
| 20 | +/* _____________ Your Code Here _____________ */ |
| 21 | + |
| 22 | +// my try |
| 23 | +type AnyOf<T extends readonly any[]> = T extends [infer El, ...infer R] |
| 24 | + ? El extends 0 | "" | false | [] | undefined | null | { [key: string]: never } |
| 25 | + ? AnyOf<R> |
| 26 | + : true |
| 27 | + : false; |
| 28 | + |
| 29 | + // after some thinking |
| 30 | +type AnyOf2<T extends readonly any[]> = T[number] extends 0 | "" | false | [] | undefined | null | { [key: string]: never } |
| 31 | + ? false |
| 32 | + : true; |
| 33 | + |
| 34 | +type Sample1 = AnyOf<[1, "", false, [], {}]>; // expected to be true. |
| 35 | +// ^? |
| 36 | +type Sample2 = AnyOf<[0, "", false, [], null, undefined]>; // expected to be false. |
| 37 | +// ^? |
| 38 | + |
| 39 | +/* _____________ Test Cases _____________ */ |
| 40 | +import type { Equal, Expect } from "@type-challenges/utils"; |
| 41 | + |
| 42 | +type cases = [ |
| 43 | + Expect< |
| 44 | + Equal<AnyOf<[1, "test", true, [1], { name: "test" }, { 1: "test" }]>, true> |
| 45 | + >, |
| 46 | + Expect<Equal<AnyOf<[1, "", false, [], {}]>, true>>, |
| 47 | + Expect<Equal<AnyOf<[0, "test", false, [], {}]>, true>>, |
| 48 | + Expect<Equal<AnyOf<[0, "", true, [], {}]>, true>>, |
| 49 | + Expect<Equal<AnyOf<[0, "", false, [1], {}]>, true>>, |
| 50 | + Expect<Equal<AnyOf<[0, "", false, [], { name: "test" }]>, true>>, |
| 51 | + Expect<Equal<AnyOf<[0, "", false, [], { 1: "test" }]>, true>>, |
| 52 | + Expect< |
| 53 | + Equal<AnyOf<[0, "", false, [], { name: "test" }, { 1: "test" }]>, true> |
| 54 | + >, |
| 55 | + Expect<Equal<AnyOf<[0, "", false, [], {}, undefined, null]>, false>>, |
| 56 | + Expect<Equal<AnyOf<[]>, false>> |
| 57 | +]; |
| 58 | + |
| 59 | +/* _____________ Further Steps _____________ */ |
| 60 | +/* |
| 61 | + > Share your solutions: https://tsch.js.org/949/answer |
| 62 | + > View solutions: https://tsch.js.org/949/solutions |
| 63 | + > More Challenges: https://tsch.js.org |
| 64 | +*/ |
0 commit comments