简体   繁体   English

TSLint双重vs三重平等

[英]TSLint double vs triple equality

I know that a single equality sign means assignment; 我知道一个单一的平等标志意味着分配; double means equality; 双重意味着平等; and triple means equality and the same type. 和三重意味着平等和相同的类型。

What I don't understand why the typescript linter would want me to use triple equality signs in this case: 我不明白为什么打字稿linter会让我在这种情况下使用三重等号:

function gcf(a: number, b: number): number
{
    return (b == 0) ? (a) : (gcf(b, a % b));
}

TsLint: == should be === TsLint:==应该是===

I know that 0 is a number and I also know that b is a number (or else I'll get a compilation error). 我知道0是一个数字,我也知道b是一个数字(否则我会得到一个编译错误)。 So why would I want to use triple equality signs in this case? 那么为什么我要在这种情况下使用三重等号?

Types can't save you from all errors caused by == . 类型无法使您免于因==导致的所有错误。 Particularly since undefined and null are compatible with all types. 特别是因为undefinednull所有类型兼容。 eg the following is an incorrect if : 例如,以下是不正确的:

var foo:number = null; 

if (foo == undefined) { 
    console.log('is undefined'); // actually null  
}

For more info on why these are equal https://stackoverflow.com/a/359509/95190 有关为何这些是平等的更多信息, 请访问https://stackoverflow.com/a/359509/95190

Personally : I have had this rule disabled and never had any issues. 个人 :我已禁用此规则,从未遇到任何问题。 I don't compare with true/false/null/undefined , just if them. 我不比较true/false/null/undefined只是, if他们。 And typescript prevents comparing strings and numbers so that is not an error I need to deal with. 打字稿可以防止比较stringsnumbers因此这不是我需要处理的错误。

Using the triple equality operator also saves you in cases when the resultant Javascript may be called from an outside file (ie outside of the TypeScript environment). 使用三重等式运算符还可以节省您从外部文件(即TypeScript环境之外)调用结果Javascript的情况。 Pure JS files aren't processed by tslint, and by 'requiring' the triple equality, tslint makes the resultant Javascript file that little more resiliant. 纯粹的JS文件不是由tslint处理的,并且通过“要求”三重相等,tslint使得生成的Javascript文件更具弹性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM