0

I have the following problem: within the following code, I'm trying to check, if the variable result is true or false:

    const result: boolean = await this.sqlConnector.validatePassword
        (this.userData.getUserId(), validatorContext.recognized.value);
    // Returns string
    console.log(typeof(result));

The function sqlconnector.validatePassword is also returning a boolean. The header of the function looks like that:

public validatePassword (userId: string, userInput: string): Promise <boolean> 

However, the typeof(result) function is saying, that the variable is from type string. This finally leads to the fact that the following if statement always fails.

    // always false because no boolean
    if (result === true) {
        return true;
    } else {

What is the reason for this?

11
  • well why does sqlConnector.validatePassword return a string? Commented Jan 28, 2019 at 21:11
  • I dont know :D. I have set the return value to boolean. It looks like that: return new Promise ((res, rej) => { this.con.query(getResult, (err, result) => { if (err) { rej (false) } else { res (result[0].isSecretCorrect); } }); }) In both cases, im receiving an string. Commented Jan 28, 2019 at 21:14
  • 2
    TypeScript types are compile-time, not run-time. So it doesn't matter that you've declared result as a boolean. Commented Jan 28, 2019 at 21:17
  • 1
    TypeScript doesn't convert your values, since it is just JavaScript superset. And your app actually runs JS. So, if some function returns string, you'll get a string, despite boolean annotation in TS code. Commented Jan 28, 2019 at 21:19
  • 1
    Then the only answer I can come up with, that result[0].isSecretCorrect is actually a string at the moment, when it passes to the res function. Commented Jan 28, 2019 at 21:35

1 Answer 1

2

Looks like you are being passed back a string value. This should be fixed within the code that is returning the response. As a temporary measure you could check the string for what it is and use it in a similar way. Should hold while response if fixed.

if (typeof result === "string" && result === "true") {
    return true;
} 

you could also check the response and change it accordingly.

let result: any = await this.sqlConnector.validatePassword
(this.userData.getUserId(), validatorContext.recognized.value);


if (typeof result === 'string'){
  result = result === "true";
}

Most of all though I would recommend getting the response to be returned as type Boolean if that is what is intended allowing for simple checks like.

if (result) // as long as result is true
{
  //you will end up here
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.