TypeScript 将布尔值转换为字符串
TypeScript converts boolean to string
我有以下问题:在下面的代码中,我试图检查变量结果是真还是假:
const result: boolean = await this.sqlConnector.validatePassword
(this.userData.getUserId(), validatorContext.recognized.value);
// Returns string
console.log(typeof(result));
函数 sqlconnector.validatePassword
也返回一个布尔值。函数的 header 看起来像这样:
public validatePassword (userId: string, userInput: string): Promise <boolean>
然而,typeof(result)
函数表示,该变量来自字符串类型。
这最终导致下面的 if 语句总是失败。
// always false because no boolean
if (result === true) {
return true;
} else {
这是什么原因?
看起来您正在被传回一个字符串值。这应该在返回响应的代码中修复。作为临时措施,您可以检查字符串的内容并以类似的方式使用它。如果已修复,应在响应时保持。
if (typeof result === "string" && result === "true") {
return true;
}
您还可以检查响应并相应地进行更改。
let result: any = await this.sqlConnector.validatePassword
(this.userData.getUserId(), validatorContext.recognized.value);
if (typeof result === 'string'){
result = result === "true";
}
最重要的是,如果允许进行简单检查,我建议将响应作为布尔类型返回。
if (result) // as long as result is true
{
//you will end up here
}
我有以下问题:在下面的代码中,我试图检查变量结果是真还是假:
const result: boolean = await this.sqlConnector.validatePassword
(this.userData.getUserId(), validatorContext.recognized.value);
// Returns string
console.log(typeof(result));
函数 sqlconnector.validatePassword
也返回一个布尔值。函数的 header 看起来像这样:
public validatePassword (userId: string, userInput: string): Promise <boolean>
然而,typeof(result)
函数表示,该变量来自字符串类型。
这最终导致下面的 if 语句总是失败。
// always false because no boolean
if (result === true) {
return true;
} else {
这是什么原因?
看起来您正在被传回一个字符串值。这应该在返回响应的代码中修复。作为临时措施,您可以检查字符串的内容并以类似的方式使用它。如果已修复,应在响应时保持。
if (typeof result === "string" && result === "true") {
return true;
}
您还可以检查响应并相应地进行更改。
let result: any = await this.sqlConnector.validatePassword
(this.userData.getUserId(), validatorContext.recognized.value);
if (typeof result === 'string'){
result = result === "true";
}
最重要的是,如果允许进行简单检查,我建议将响应作为布尔类型返回。
if (result) // as long as result is true
{
//you will end up here
}