Вопрос

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:

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

TsLint: == should be ===

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?

Это было полезно?

Решение

Types can't save you from all errors caused by ==. Particularly since undefined and null are compatible with all types. e.g. 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

Personally : I have had this rule disabled and never had any issues. I don't compare with true/false/null/undefined, just if them. And typescript prevents comparing strings and numbers so that is not an error I need to deal with.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top