Reputation: 1070
I have a simple check where I want to check if the given variable is >=0.
public print(value: any): void {
if(value >= 0) {
console.log('Greater than zero')
}
}
The catch here is when the incoming variable has value null, then it will become truthy and log the statement. Is there a clean way to avoid it, but not adding extra checks?
Upvotes: 4
Views: 7737
Reputation: 1580
In JavaScript, I usually use the following:
`${value}` >= 0
// or
parseInt(value) >= 0
in TypeScript you can most likely use:
public print(value: any): void {
if (+`${value}` >= 0) {
console.log('Not less than zero')
}
}
Upvotes: 0
Reputation: 28977
You can employ a type guard that will assure the compiler that you're not handling a null
but a number. Moreover, it will make the code more correct, since with value: any
this means you might get a boolean or a string passed in:
public print(value: any): void {
if (typeof value === "number") {
//value is definitely a number and not null
if (value >= 0) {
console.log('Greater than zero')
}
}
}
Now the code specifically verifies that you do get a number and then checks if it's more than or equal to zero. This means that a null
or a non-number value would not be processed.
The type guard condition can be combined with the other for brevity:
public print(value: any): void {
if (typeof value === "number" && value >= 0) {
console.log('Greater than zero')
}
}
Or extracted on its own to just reduce the nesting:
public print(value: any): void {
if (typeof value !== "number")
return;
//value is definitely a number and not null
if (value >= 0) {
console.log('Greater than zero')
}
}
Upvotes: 2
Reputation: 2677
If you codebase does not allow the use of null
, just use undefined
and use an implicit conversion, like so:
public print(value: any): void {
if(value != undefined && value >= 0) {
console.log('Greater than zero')
}
}
This works because null == undefined
(the double equals creates a type conversion, while the triple equals does not).
Upvotes: 1
Reputation: 3138
I don't see why you don't want to add a null-check.
An alternative is to use number
instead of any
but it will work only if your ts.conf
enables strict null checks.
function print(value: number): void {
if(value >= 0) {
console.log('Greater than zero')
}
}
print(null) // won't compile with strict null checks
Upvotes: 1