microsoft/TypeScript

Incorrect propagation of boolean property value

bjouhier opened this issue · 2 comments

TypeScript Version: 2.0.3

Code

function foo(x: boolean, arg: any) {
    if (x) arg.val = true;
}

function bar(x: boolean) {
    var arg = {
        val: false,
    };
    arg.val = false;
    foo(x, arg);
    if (arg.val === true) console.log('test is true!');
}

bar(true);

Expected behavior:

Code should compile without errors.

Actual behavior:

bug.ts(11,9): error TS2365: Operator '===' cannot be applied to types 'false' and 'true'.

compiler infers that arg.val is alwaysfalse in the if test. This is wrong because foo(x, arg) modifies arg.val.

Got it.

I only hit that problem once in 43 klocs, and the fix was really easy. I just removed the === true part from the test. Testing booleans with x === true is a bad habit anyway.

I like the optimistic approach descrbed in #9998. I see it as a tacit encouragement to reduce side-effects in code. When this kind of problem happens (when type inference is misled), it is probably a good idea to review the code and eliminate the nasty side-effects. If the TS compiler missed the mutation, it's likely that a developper will also miss it when reading the code.