typescript类型体操 - AnyOf

题目

中文

在类型系统中实现类似于 Python 中 any 函数。类型接收一个数组,如果数组中任一个元素为真,则返回 true,否则返回 false。如果数组为空,返回 false

例如:

type Sample1 = AnyOf<[1, '', false, [], {}]>; // expected to be true.
type Sample2 = AnyOf<[0, '', false, [], {}]>; // expected to be false.

English

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 AnyOf<T extends readonly any[]> = T[number] extends
    | ''
    | 0
    | []
    | false
    | { [P in any]: never }
    ? false
    : true;

在线演示

posted @ 2022-09-08 22:01  Laggage  阅读(62)  评论(0编辑  收藏  举报