Skip to content

Incorrect propagation of boolean property value #11393

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
bjouhier opened this issue Oct 5, 2016 · 2 comments
Closed

Incorrect propagation of boolean property value #11393

bjouhier opened this issue Oct 5, 2016 · 2 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@bjouhier
Copy link

bjouhier commented Oct 5, 2016

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.

@RyanCavanaugh
Copy link
Member

See #9998

@bjouhier
Copy link
Author

bjouhier commented Oct 5, 2016

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.

@bjouhier bjouhier closed this as completed Oct 5, 2016
@RyanCavanaugh RyanCavanaugh added the Question An issue which isn't directly actionable in code label Oct 5, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

2 participants