javascript - 函数中带有字符串的打字稿条件总是返回 false
问题描述
我在函数的打字稿条件中有一个奇怪的错误。有我当前的代码。我的参数来自外部:
getLevel(validation: string, status: string): string {
let card = "";
if (validation == "A") {
if (!status) {
card = "card-success";
} else {
switch (status) {
case "S":
// console.log("case s");
card = "card-success";
break;
case "C":
case "U":
case "V":
// console.log("case cuv");
card = "card-low";
break;
default:
// console.log("case default");
card = "card-success";
break;
}
}
}
return card;
}
为了测试我试过这个:
getLevel(validation2: string, status2: string): string {
let card = "";
const validation = "A"; // for test purpose
const status = "U"; // for test purpose
if (status == status2) { // for test purpose
console.log("aeae"); // not working
}
console.log(status); //display U
console.log(status2); // display U
console.log(typeof status); //display string
console.log(typeof status2); // display string
if (validation == "A") {
switch (status) {
case "S":
console.log("case s");
card = "card-success";
break;
case "C":
case "U":
case "V":
console.log("case cuv");
card = "card-low"; // should display this one and works with variables defined within the function
break;
default:
console.log("case default"); // display this one with data from function args
card = "card-success";
break;
}
}
return card;
}
因此,当我在代码中尝试使用变量时,它可以工作,但不能使用我的参数。我也尝试了一个简单的 if 语句,但它也不起作用。有我的调试器截图
解决方案
你在声明const status = "U"
. 如果您将鼠标悬停status
在 IDE 中,它会显示类型status
为"U"
. 这意味着该status
变量只能是"U"
,不能是其他字符或字符串。如果你想手动对打字稿说 status 不应该是 type "U"
,你可以说:
const status : string = "U"
或者以一种更合乎逻辑的方式,声明您的status
变量,let
以便打字稿知道您可能会更改status
变量的值。
let status = "U"
function getLevel(validation2: string, status2: string): string {
let card = "";
const validation = "A";
let status = "U";
if (status == status2) {
console.log("aeae"); // not working
}
console.log(status); //display U
console.log(status2); // display U
console.log(typeof status); //display string
console.log(typeof status2); // display string
if (validation == "A") {
switch (status) {
case "S":
console.log("case s");
card = "card-success";
break;
case "C":
case "U":
case "V":
console.log("case cuv");
card = "card-low"; // should display this one and works with variables defined within the function
break;
default:
console.log("case default"); // display this one with data from function args
card = "card-success";
break;
}
}
return card;
}
推荐阅读
- qt - QtQuick Grid,鼠标事件不会传播到相邻的鼠标区域
- java - Android Java Webview 操作 XHR/AJAX-Request
- php - WordPress:从父类别获取子类别
- css - 多个“子应用程序”合二为一(CSS 冲突)
- mysql - 如何通过分组计算多行的百分比
- sql-server - 我可以在不指定表名的情况下从多个 SQL Server 表中进行选择吗
- events - 如何在事件源架构中使用的事件存储中映射关系?
- r - 如何在 R 中按集群设置观察值的最高可能均匀分布
- linux - ssh -t 在 vps 上由 docker 托管的 gitlab 服务器上不断询问密码
- sql - 在 MS Access 中计数不同 - 如何计算至少具有某种类型的活动的帐户数?