jdprepaprop
jdprepaprop

Reputation: 51

Don't understand why this boolean comparison is failing

Fairly new to angular, and not the most experienced javascript/typescript dev. Mostly smaller projects.

Currently have no idea why this comparison is failing.

if(data.success == true) {
      //do stuff
    }

where the data structure I'm getting is defined as

export class RegResponse {
  success : boolean;
  error : string;
  constructor(success: boolean, error: string){
    this.success = success;
    this.error = error;
  }

and console.log of data.success is true.

console.log(typeof(data.success)) is string (for some reason)? but if I try a string comparison on the variable it declares throws an error for operations not applicable to booleans.

So I'm perplexed why this isn't working.

This as a work around works, but I don't understand why the obvious first comparison is failing.

if(data.success + '' === 'true') {

Upvotes: 2

Views: 616

Answers (2)

Christian Vincenzo Traina
Christian Vincenzo Traina

Reputation: 10374

The fact that you declare success as boolean, doesn't mean that your service will return you a boolean. If the endpoint returns a string, then it is a string.

Typescript is used for type definition, it's just a way to say "I expect a string here and a boolean there", but if the source is unknown then you have to do the check by yourself.

When you assign data.success you can do something like this:

data.success = response.success === 'true';

As a further solution, if you are using Angular 4+ you can implement a safe type-checking system just specifying the interface in the Http client.

You can read more in the official guide:

getReg() {
  // it will return an Observable of RegResponse
  return this.http.get<RegResponse>(this.configUrl);
}

But it won't help you converting strings in booleans, this will just fail if you expect something and get something other!

Upvotes: 5

RDyego
RDyego

Reputation: 276

if "data.success" is only true, false, 'true' or 'false', you can try: if(JSON.parse(data.success)) { //code }

Upvotes: 0

Related Questions