0

I have the following code in a typescript module:

if (!(wholeWords === true)) { 
  console.log("Any part", wholeWords); 
} else { 
  console.log("Whole word", wholeWords); }

The "wholeWords" parameter is declared in the argument list for the method as a boolean. (wholeWords: boolean)

In my browser, I see the following:

Any part true

How is this possible?!?

2
  • 2
    Side note, why not write this as if (wholeWords) {} else {} - actual suggestion - can you log wholeWords before the check? If you set wholeWords = true; right before the logic, does it work? Commented Oct 31, 2017 at 19:14
  • 1
    Add console.log(typeof wholeWords) before that code and see what it returns. I'm making a wild guess that wholeWords is actually the string value "true" at runtime, and where you think you've guaranteed that wholeWords is a boolean is not actually doing it. Provide more of your code if you want more help. Commented Oct 31, 2017 at 19:16

2 Answers 2

1

I suspect wholeWords is the string "true" and not the boolean value true

var wholeWords = "true";

if (!(wholeWords === true)) { 
  console.log("Any part", wholeWords); 
} else { 
  console.log("Whole word", wholeWords);
}

Sign up to request clarification or add additional context in comments.

2 Comments

I think you're right. I have an Angular dropdown as follows: <select class="form-control" [(ngModel)]="wholeWords"> <option value="true">Whole Words Only</option> <option value="true">Any Match</option> </select> That dropdown is bound to a boolean value that's used in the filter. However, I was able to confirm that it's passing a string. However, I'm confused. Typescript is supposed to enforce STRONG TYPING. What's happening here?
Typescript compiles to plain JS, which has no types. So there is no runtime enforcement of your types. In this case, what likely happened is that somewhere you had a value of type any that got assigned to boolean. Typescript is okay with that since an any certainly can be a boolean. But, in this case, it turned out to be a string. In other words, to get the most from typescript, make sure you limit the use of any as much as you possibly can.
0

By comparing using === you're checking if it's equal value and equal type.

Try with:

if (!(wholeWords == true)) { 
  console.log("Any part", wholeWords); 
} else { 
  console.log("Whole word", wholeWords);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.