-
Notifications
You must be signed in to change notification settings - Fork 391
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
「重学TS 2.0 」TS 练习题第四十题 #60
Comments
type NotEmptyObject<T> = T extends {} ? ({} extends T ? false : true) : true;
type Flasy = 0 | "" | false | [];
type AnyOf<T extends any[]> = T extends [infer First, ...infer Rest]
? First extends Flasy
? AnyOf<Rest>
: NotEmptyObject<First>
: false;
type A0 = AnyOf<[]>; // false
type A1 = AnyOf<[0, "", false, [], {}]>; // false
type A2 = AnyOf<[1, "", false, [], {}]>; // true |
写得烂了点 type FaslyUnion = 0 | "" | false | 0n | null | undefined;
type AnyOfUnion = FaslyUnion | [];
type IsEmptyObject<T> = T extends {} ? ({} extends T ? true : false) : false;
type AnyOf<T extends any[]> = Len<T> extends 0
? false
: T[0] extends AnyOfUnion
? AnyOf<Tail<T>>
: IsEmptyObject<T[0]> extends true
? false
: true;
type A02 = AnyOf<[]>; // false
type A12 = AnyOf<[0, "", false, [], {}]>; // false
type A22 = AnyOf<[1, "", false, [], {}]>; // true |
type NotEmptyObject<T> = T extends {} ? ({} extends T ? false : true) : true;
type Flasy = 0 | "" | false | [];
type AnyOf<T extends any[]> = T extends [infer First, ...infer Rest]
? [First] extends [Flasy]
? AnyOf<Rest>
: NotEmptyObject<First>
: false;
type A0 = AnyOf<[]>; // false
type A1 = AnyOf<[0, '', false, [], {}]> // false
type A2 = AnyOf<[1, "", false, [], {}]> // true
type A3 = AnyOf<[0, "" | 2, false, [], {}]> // true 注意 元组中存在联合类型的问题。因此比对空对象的时候[] 转换成元组去extends比对,避免联合类型发生分布执行 |
基本类型也都属于对象类型 |
// 先extends infer,判断是否空数组 type Trim = T extends '' ? true : false; type EmptyArr = T extends [] ? true : false type EmptyObj = keyof T extends never ? true : false type isFalsy = Zero extends true type AnyOf<T extends any[]> = EmptyArr extends true // 你的实现代码 type A0 = AnyOf<[]>; // false |
实现
AnyOf
工具类型,只要数组中任意元素的类型非 Falsy 类型、{}
类型或[]
类型,则返回true
,否则返回false
。如果数组为空的话,则返回false
。具体的使用示例如下所示:The text was updated successfully, but these errors were encountered: