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 一些有趣的增强类型 #6

Open
tianzhich opened this issue Jun 3, 2021 · 1 comment
Open

TS 一些有趣的增强类型 #6

tianzhich opened this issue Jun 3, 2021 · 1 comment
Labels
typescript TS topics

Comments

@tianzhich
Copy link
Owner

tianzhich commented Jun 3, 2021

Equals 的实现

来源于:microsoft/TypeScript#27024 (comment)

export type Equals<X, Y> =
    (<T>() => T extends X ? 1 : 2) extends
    (<T>() => T extends Y ? 1 : 2) ? true : false;
@tianzhich tianzhich added the typescript TS topics label Jun 3, 2021
@tianzhich
Copy link
Owner Author

解释一下,当泛型 T 类型未知时,对这部分条件类型 T extends X ? 1 : 2 的推断会被推迟。而对于类型 <T>() => T extends X ? 1 : 2,由于其是一个函数,返回值包含了推迟的条件类型,所以该类型也被推迟。

这样一来,判断类型 <T>() => T extends X ? 1 : 2 是否可赋值(extends)给 <T>() => T extends Y ? 1 : 2条件就是:

  • 第一个 T 可赋值给第二个 T,或反之
  • XY 类型完全相同
  • 1 可以赋值给 1
  • 2 可以赋值给 2

// Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
// one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
// and Y1 is related to Y2.

可以看到,第 1 个条件和第 3-4 个条件完全成立,而条件 2 则正好是 Equals 类型实现的关键。

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

No branches or pull requests

1 participant