Skip to content
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 练习题第三十九题 #59

Open
semlinker opened this issue Sep 25, 2021 · 5 comments
Open

「重学TS 2.0 」TS 练习题第三十九题 #59

semlinker opened this issue Sep 25, 2021 · 5 comments

Comments

@semlinker
Copy link
Owner

实现 IsAny 工具类型,用于判断类型 T 是否为 any 类型。具体的使用示例如下所示:

type IsAny<T> = // 你的实现代码

type I0 = IsAny<never> // false
type I1 = IsAny<unknown> // false
type I2 = IsAny<any> // true

请在下面评论你的答案

@zhaoxiongfei
Copy link

zhaoxiongfei commented Sep 26, 2021

type IsAny<T> = 0 extends 1 & T ? true : false;

type I0 = IsAny<never>; // false
type I1 = IsAny<unknown>; // false
type I2 = IsAny<any>; // true

思路: 利用任何类型和any交叉都等于any来实现。

@981377660LMT
Copy link

// unknown 只能赋给 unknown 或者 any
type IsAny<T> = [unknown] extends [T] ? ([T] extends [string] ? true : false) : false

type I0 = IsAny<never> // false
type I1 = IsAny<unknown> // false
type I2 = IsAny<any> // true

@jackwangwj
Copy link

type IsAny = [unknown] extends [T]
? [T] extends [string]
? true
: false
: false

type I0 = IsAny // false
type I1 = IsAny // false
type I2 = IsAny // true

@ChangerHe
Copy link

// 解法: any的特性是与任意值并得出的值为本身
// 我们随便找两个不同的值即可
type IsAny<T> = 'a' extends 'b' & T ? true : false

@ChuTingzj
Copy link

ChuTingzj commented Jun 14, 2022

几何之美

// 实现 IsAny 工具类型,用于判断类型 T[] 是否为 any 类型。具体的使用示例如下所示:
// type IsAny<T[]> = // 你的实现代码
// type I0 = IsAny<never> // false
// type I1 = IsAny<unknown> // false
// type I2 = IsAny<any> // true

type IsAny<T> = T[] extends never[]
  ? false
  : T[] extends string[]
  ? T[] extends number[]
    ? T[] extends boolean[]
      ? T[] extends object[]
        ? T[] extends unknown[]
          ? T[] extends symbol[]
            ? T[] extends null[]
              ? T[] extends undefined[]
                ? T[] extends bigint[]
                  ? T[] extends any[]
                    ? true
                    : false
                  : false
                : false
              : false
            : false
          : false
        : false
      : false
    : false
  : false
type I00 = IsAny<never> // false
type I11 = IsAny<unknown> // false
type I22 = IsAny<any> // true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants