One way to ensure that you are dealing with a number and not null is by using a type guard. This will make your code more accurate, as having `value: any` can lead to receiving a boolean or string:
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')
}
}
}
Playground Link
This approach specifically confirms the input as a number before checking its value against zero. Therefore, null or non-number values will be excluded from further processing.
The type guard condition can also be condensed with the main logic for succinctness:
public print(value: any): void {
if (typeof value === "number" && value >= 0) {
console.log('Greater than zero')
}
}
Playground Link
Alternatively, you can extract the type guard check into a separate block to reduce 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')
}
}
Playground Link