[Typescript] 39. Medium - AnyOf

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.

 

type Falsy = false | 0 | '' | [] | Record<PropertyKey, never>
type AnyOf<T extends readonly any[]> = T extends [infer First, ...(infer REST)]
  ? First extends Falsy 
    ? AnyOf<REST>
    : true
  : false;

 

type AnyOf<T extends readonly any[]> = T extends Array<0 | '' | false | [] | Record<PropertyKey, never>> ? false : true

 

posted @ 2022-09-28 01:39  Zhentiw  阅读(6)  评论(0编辑  收藏  举报