문제

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