最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Are there type-safe equivalents to the comparison operators in JavaScript? - Stack Overflow

programmeradmin2浏览0评论

I just tried the following in a node.js console:

> 5 <= "5"
true

Which means that the = part of the <= is treated the same way == is, not ===. Which made me immediately try <== hoping it would do what you would hope it would. But it doesn't exist.

Then I tried the following:

> 5 < "6"
true

Then I started to observe even stranger behaviour:

> 5 < [6]
true

Which brings up a more important question: are there type-safe equivalents to <, >, <=, and >=?

I just tried the following in a node.js console:

> 5 <= "5"
true

Which means that the = part of the <= is treated the same way == is, not ===. Which made me immediately try <== hoping it would do what you would hope it would. But it doesn't exist.

Then I tried the following:

> 5 < "6"
true

Then I started to observe even stranger behaviour:

> 5 < [6]
true

Which brings up a more important question: are there type-safe equivalents to <, >, <=, and >=?

Share Improve this question edited May 28, 2014 at 2:00 Sahand asked May 28, 2014 at 1:58 SahandSahand 2,1751 gold badge19 silver badges25 bronze badges 2
  • 5 I edited your title. Your previous title was wondering into "Hey, could a language designer tell me why this feature isn't here?" and this is more, "How do I do type-safe parison in JavaScript? – George Stocker Commented May 28, 2014 at 2:00
  • Long story short: no there is not (built-in). – Felix Kling Commented May 28, 2014 at 2:01
Add a ment  | 

2 Answers 2

Reset to default 8

No, but it can be handled by correct use of existing language features to type check.

Comparison is ideally two state logic. Either a<b or it is not. The problem is that bining type checking with parison changes two state logic into three state (true/false/inparable). To return one of three outes would no longer be a simple Boolean.

A pre-check on types can already be implemented with typeof or instanceOf

If parisons must be type-appropriate, and there is no code written to deal with mismatches, then an error can be thrown to stop execution as in the following example:

if (typeof(a) !== typeof(b)) {
    throw `type mismatch in some_function(), types: ${typeof(a)}, ${typeof(b)}`;
}

// now the next operation is "safe"
if (a <= b) {
    do_something();
} else {
    do_the_other_thing();
}

Later when there is error handling code, you can replace the throw or keep the throw and use try/catch.

No, there's nothing built in to do so.

Consider:

// I invented ~ as the non type coercion operator
5 <~ 6
5 <~ '6'

Both of these return false, but the return values don't really mean the same thing. In the second case, it likely wouldn't have even pared the values.

发布评论

评论列表(0)

  1. 暂无评论