运算符 '==' 不能应用于 Typescript 2 中的类型 x 和 y [英] Operator '==' cannot be applied to types x and y in Typescript 2

查看:23
本文介绍了运算符 '==' 不能应用于 Typescript 2 中的类型 x 和 y的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TypeScript 版本: 2.0.2.0

代码我知道代码有点愚蠢,但实际上我的代码中有这些测试(使表达式访问者),我真的认为这些应该立即运行并编译.

Code I know the code is a bit stupid, but I actually have these kind of tests in my code (making an expression visitor) and I really think these should fly and compile right away.

var a: boolean = (true == false);
var b: boolean = (5 == 2);

相反,它抱怨操作数 equal 不能应用于类型true"、false"、5"和2".标记它们不是布尔值或数字,它们实际上是真"、假"、5"、2"的类型.我知道'string'和'boolean'类型不能比较,但是嘿,5实际上是一个数字,而不是'5'类型还是我弄错了?

Instead it complains that operand equal cannot be applied to types 'true', 'false', '5' and '2'. Mark that they are not boolean or number, they are actually a types of 'true','false','5','2'. I know that types 'string' and 'boolean' cannot be compared, but hey, 5 is actually a number, not type '5' or am I mistaken?

这虽然编译.

let x = 2;
var a: boolean = 5 == x;
var b: boolean = <number>5 == <number>2;

我是否遗漏了什么,为什么不将 5 和 2 视为类型数字"?

Am I missing something, why arent't 5 and 2 considered as type 'number' ?

预期行为:应该编译

实际行为:导致编译错误,提示操作数 '==' 不能应用于类型 '<first argument>'和'<第二个参数>'

Actual behavior: Results in a compile error saying 'Operand '==' cannot be applied to types '<first argument>' and '<second argument>'

背景 我在 typescript 中遇到了这个问题,定义它应该是这样的,但是怎么会呢?https://github.com/Microsoft/TypeScript/issues/6167

Background I came over this issues in typescript defining that it should be like this, but how come? https://github.com/Microsoft/TypeScript/issues/6167

推荐答案

文字类型有很多优点,因为它可以让编译器使类型尽可能窄.您的用例很少出现,但希望类型尽可能窄渗透到语言的整个设计中.所以,是的,虽然在这种特定情况下它会让你的生活变得更加困难,但它在整个语言中是有意义的.为了支持这个罕见的用例,用户将不得不忍受一种更糟糕的语言.

Literal types have many advantages, as it lets the compiler make types as narrow as possible. Your use case is one that comes up very rarely, but wanting types to be as narrow as possible permeates the entire design of the language. So yes, while it makes your life harder in this one specific case, it makes sense in the language as a whole. Users would have to suffer a significantly worse language, just to support this one rare use case.

不幸的是,您将不得不使用您在第二个示例中建议自己的显式类型.我认为这个问题永远不会被修复,因为大多数用户希望如果他们尝试这样做,语言会大喊大叫.在大多数情况下,这可能是错误的迹象.

Unfortunately, you will have to use the explicit typing you suggest yourself in the second example. I don't see this ever being fixed, because the majority of users wants the language to yell if they try to do this. It's probably the sign of a bug in a large majority of cases.

这篇关于运算符 '==' 不能应用于 Typescript 2 中的类型 x 和 y的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆