Reputation: 7004
I've got a pretty simple situation that's got me puzzled. I'm passing a parameter to an express http get function. It's used in a query, so I'm making sure it's a number (and thus I'm safe from SQL injection).
Due to my client data structure, I convert these numbers to strings. So I accidentally passed a string instead of a number. It caused my application to pass, as invoiceId evaluated to undefined, and the query failed.
To protect against this, I have added a null check. Here's a working example (with some messing about so there's no compile error casting a string to a number):
(Note, it was discovered the value was being passed as the string value "undefined", hence the confusion. I still have the issue of not being able to catch it as typescript forbids me from checking if invoiceId is a string value as it should be a number. I assumed is
enforced type!)
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);
However, in the situation where a string invoiceId is provided, it doesn't not trigger the invoiceId == null statement. This is the output:
getting for invoice undefined
I've tried checking invoiceId == undefined
, and typeof invoiceId == null
just if(invoiceId)
to check if it's "truthy" but everything get's passed this check.
Any idea why, and how I can catch it?
Upvotes: 2
Views: 5582
Reputation: 141542
I still have the issue of not being able to catch it as typescript forbids me from checking if invoiceId is a string value as it should be a number.
One approach is to check whether the value is of type number
or has a null
value.
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.")
}
Output:
Some string is of type string and needs to be of type number.
Any idea why...
Casting to a number happens only at compile time and has no impact at runtime. If the client application inputs a string at runtime, then the variable will be a string at runtime, which is neither a typeof undefined
nor null
.
You can find out more by running the above in TypeScript play.
Upvotes: 4