typescript - 未定义的数字(从字符串转换)通过空值检查
我有一个相当简单的情况,但让我感到困惑。我正在向 Express HTTP GET 函数传递一个参数。它用于查询,所以我确保它是一个数字(因此我免受 SQL 注入的影响)。
由于我的客户端数据结构,我将这些数字转换为字符串。所以我不小心传了一个字符串而不是数字。这导致我的应用程序跳过了,因为 invoiceId 被评估为 undefined,查询失败了。
为了防止这种情况,我添加了一个空值检查。这里有一个可运行的示例(做了一些修改,以避免将字符串转换为数字时出现编译错误):
(注意,发现该值被作为字符串值“undefined”传递,因此造成了混淆。我仍然有无法捕捉它的问题,因为 TypeScript 不允许我检查 invoiceId 是否为字符串值,因为它应该是一个数字。我本以为 is 会强制类型!)
class IBadInput { value: any };
var badInput = { value: "undefined" } as IBadInput;
var invoiceId = badInput.value as number;
if (typeof invoiceId == 'undefined' || invoiceId == null)
{
console.log("inoice id not provided");
}
console.log("getting for invoice", invoiceId);
然而,在提供字符串 invoiceId 的情况下,它不会触发 invoiceId == null 语句。输出如下:
getting for invoice undefined
我尝试过检查 invoiceId == undefined,和 typeof invoiceId == null,只是 if(invoiceId) 来检查它是否为“真值”,但是所有情况都通过了这个检查。
有想过为什么会这样,以及我如何才能抓住它吗?
答案#1
我仍然有一个问题,就是无法捕捉它,因为 TypeScript 不允许我检查 invoiceId 是否是字符串值,而它应该是一个数字。
一种方法是检查该值是否为 number 类型或是否具有 null 值。
let input: any = "Some string";
let invoiceId = input as number;
if (typeof invoiceId !== 'number' || invoiceId === null)
{
document.write(invoiceId.toString() + ' is of type ' + (typeof invoiceId));
document.write(" and needs to be a non-null value of type number.")
}
输出 :
Some string is of type string and needs to be of type number.
有什么想法为什么……
类型转换为数字仅发生在编译时,对运行时没有影响。如果客户端应用在运行时输入一个字符串,那么该变量在运行时将是一个字符串,这既不是 typeof undefined 也不是 null。
你可以通过在 TypeScript Playground 中运行上述内容来了解更多信息。
