type-challenges / type-challenges

Collection of TypeScript type challenges with online judge
https://tsch.js.org/
MIT License
43.31k stars 4.7k forks source link

949 - AnyOf #953

Open gxy01 opened 3 years ago

gxy01 commented 3 years ago
type Bool<T>=T extends 1 ?true:
                  T extends string? T extends ''?false:true:
                  T extends boolean ? T:
                  T extends any[] ? (T['length'] extends 0? false:true):
                  T extends object ? (keyof T extends never? false:true):
                  false;

type AnyOf<T extends readonly any[]> = T extends [infer R,...infer Rest]? (Bool<R> extends true?true:AnyOf<Rest>):false;
MrJumpShot commented 3 years ago

Nice

xianshenglu commented 3 years ago

Well, add another way to validate empty array and object.

// type IsArrayEmpty<T extends []> = T["length"] extends 0 ? true : false
// type IsObjectEmpty<T extends {}> = keyof T extends never ? true : false

type IsArrayEmpty<T extends []> = T extends [] ? true : false
type IsObjectEmpty<T extends {}> = T extends { [key: string]: never } ? true : false