“字符串类型”的比较

发布于 2025-02-11 08:40:44 字数 603 浏览 1 评论 0原文

我尝试对类型(例如std :: Type_traits)进行静态分析,然后首先我制作了is_same<>。 类和原始类型效果很好,但是字符串字面类型具有奇怪的行为。

type is_same<A, B> = A extends B ? B extends A ? true : false : false;
type _1 = is_same<"a" | "b", "a" | "b">;
type _2 = "a" | "b" extends "a" | "b" ? "a" | "b" extends "a" | "b" ? true : false : false;

使用is_same&lt;&gt;获得的类型是_1。此类型是布尔值。 接下来,扩展is_same&lt;&gt;的结果是_2。此类型为true。 这些结果有什么区别?

我用打字稿4.7.4确认。

I tried to make static analysis of types (like std::type_traits) with TypeScript, and first I made is_same<>.
Classes and primitive types work fine, but String Literal Types have strange behavior.

type is_same<A, B> = A extends B ? B extends A ? true : false : false;
type _1 = is_same<"a" | "b", "a" | "b">;
type _2 = "a" | "b" extends "a" | "b" ? "a" | "b" extends "a" | "b" ? true : false : false;

The type obtained using is_same<> is _1. This type is boolean.
Next, The result of expanding is_same<> is _2. This type is true.
What is the difference between these results?

I confirmed with TypeScript 4.7.4.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蛮可爱 2025-02-18 08:40:44

这里的问题是由

通过按照您的方式将条件链接起来,联盟的每个成员都分别分配给下一个条件。

要停止此操作,您可以将 a 和b包装在元组中。

type is_same<A, B> = [A] extends [B] ? B extends A ? true : false : false;

Playground

The problem here is caused by Distributive Conditional Types.

By chaining the conditionals here the way you did, each member of the union is distributed individually to the next conditional.

To stop this, you can wrap A and B in a tuple.

type is_same<A, B> = [A] extends [B] ? B extends A ? true : false : false;

Playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文