TypeScript:做字符串相等的正确方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27770484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript: correct way to do string equality?
提问by Heinrich Schmetterling
If I know x and y are both of type string, is the correct way to do string equality simply x == y?
如果我知道 x 和 y 都是字符串类型,那么执行字符串相等的正确方法是 x == y 吗?
The linter I'm using complains about this.
我正在使用的 linter 抱怨这个。
回答by ssube
If you know x
and y
are both strings, using ===
is not strictly necessary, but is still good practice.
如果您知道x
并且y
都是字符串,则 using===
不是绝对必要的,但仍然是一种很好的做法。
Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string
rather than an actual string, which may complicate things.
假设两个变量实际上都是字符串,则两个运算符的功能相同。但是,TS 通常允许您传递满足所有要求的对象string
而不是实际字符串,这可能会使事情复杂化。
Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===
. Just go with that.
鉴于未来可能出现混淆或变化,您的 linter 可能在要求===
. 就这样吧。
回答by tamer badawy
The ===
is not for checking string equalit , to do so you can use the Regxp functions for example
在===
不检查字符串equalit,这样做可以使用例如Regxp功能
if (x.match(y) === null) {
// x and y are not equal
}
there is also the test
function
还有这个test
功能