typescript TSLint 双重与三重相等

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22732756/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:12:48  来源:igfitidea点击:

TSLint double vs triple equality

typescriptequality

提问by user886079

I know that a single equality sign means assignment; double means equality; and triple means equality and the same type.

我知道一个等号意味着赋值;double 意味着平等;和三重意味着相等和相同的类型。

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). So why would I want to use triple equality signs in this case?

我知道 0 是一个数字,我也知道 b 是一个数字(否则我会得到一个编译错误)。那么为什么我要在这种情况下使用三重等号呢?

采纳答案by basarat

Types can't save you from allerrors caused by ==. Particularly since undefinedand nullare compatible with alltypes. e.g. the following is an incorrect if :

类型不能救你所有的错误造成==。特别是因为undefined并且null所有类型兼容。例如,以下是不正确的,如果:

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 ifthem. And typescript prevents comparing stringsand numbersso that is not an error I need to deal with.

个人:我已禁用此规则,从未遇到任何问题。我不比较true/false/null/undefined,只是if他们。而且打字稿会阻止比较stringsnumbers因此这不是我需要处理的错误。

回答by Darren Oster

Using the triple equality operator also saves you in cases when the resultant Javascript may be called from an outside file (i.e. outside of the TypeScript environment). Pure JS files aren't processed by tslint, and by 'requiring' the triple equality, tslint makes the resultant Javascript file that little more resiliant.

在可能从外部文件(即在 TypeScript 环境之外)调用结果 Javascript 的情况下,使用三重相等运算符还可以为您节省费用。tslint 不处理纯 JS 文件,并且通过“要求”三重相等,tslint 使生成的 Javascript 文件更具弹性。