gpt4 book ai didi

typescript - TypeScript 中的双等号 (==)

转载 作者:搜寻专家 更新时间:2023-10-30 20:32:22 24 4
gpt4 key购买 nike

我一直在用 TypeScript 编写一些单元测试。示例 QUnit 测试包含:

  ok( 1 == "1", "Passed!" );
tsc编译器声称:

Operator '==' cannot be applied to types 'number' and 'string'



并退出状态 1 (尽管它确实正确地生成了 JS)。

规范说:

The <, >, <=, >=, ==, !=, ===, and !== operators

These operators require one operand type to be identical to or a subtype of the other operand type. The result is always of the Boolean primitive type.



所以看起来警告/错误是正确的。这不是更能打败强制类型的要点 ==运营商呢?是否有使用 == 的有效用例?在不会产生此警告的 TypeScript 中?

最佳答案

== 的至少一种可能的情况(即,使用类型强制)在 TypeScript 中是当预期的操作数之一是 Any 类型时:

A type S is a subtype of a type T, and T is a supertype of S, if one of the following is true: [...]

T is the Any type.



现在你可能看到了图片:任何具有 Any 参数的函数都可以安全地(好吧,更多 - 更少; == 的所有常见问题仍然适用于此)将其与任何集合类型的值与 == 进行比较。 .

关于typescript - TypeScript 中的双等号 (==),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13952941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com