Given a value of type unknown and a configuration describing if that value must be an integer or float value. I started with this function
function isValueNumber(value: unknown, isAcceptingFloatingPointNumbers: boolean) {
if (Number.isNaN(value)) {
return false;
}
if (!isAcceptingFloatingPointNumbers) {
return Number.isInteger(value);
}
return true;
}
The problem is that when I call the function like so
isValueNumber("this is not a valid number", true)
it still returns true because my check Number.isNaN is not correct ( Is Number.IsNaN() more broken than isNaN() )
Do you have any ideas how to fix this validator function?
>Solution :
This way, the function will return false if not a number :
function isValueNumber(value: unknown, isAcceptingFloatingPointNumbers: boolean) {
if (typeof value !== 'number') {
return false;
}
if (!isAcceptingFloatingPointNumbers) {
return Number.isInteger(value);
}
return true;
}