TypeScript – Check if a number is odd
TypeScript Advance Types: Exercise-5 with Solution
Write a TypeScript function that accepts a parameter of type number and returns a boolean indicating whether the number is odd. Use a type guard to check and ensure the input is a valid number.
Sample Solution:
TypeScript Code:
// Function 'isOdd' that checks if a number is odd
function isOdd(num: number): boolean {
// Type guard to check if 'num' is a finite number
if (typeof num === "number" && isFinite(num)) {
return num % 2 !== 0; // Check if the remainder is not zero (indicating an odd number)
} else {
return false; // Return false for non-numeric or infinite values
}
}
// Test the 'isOdd' function
console.log("Is 7 is odd?",isOdd(7));
console.log("Is 20 is odd?",isOdd(20));
console.log("Is -5 is odd?",isOdd(-5));
console.log("Is ABC is odd?",isOdd("ABC"));
Explanations:
In the exercise above -
- First, we define a function "isOdd()" that takes a parameter 'num' of type number.
- Inside the function, we use a type guard (typeof num === "number" && isFinite(num)) to check if num is both of type number and a finite number (not NaN, Infinity, or -Infinity).
- If the type guard passes, we use the expression num % 2 !== 0 to check if num is an odd number (i.e., its remainder when divided by 2 is not zero).
- If 'num' is not a valid number (fails the type guard) or is even, the function returns false.
- Finally, we test the "isOdd()" function with different numeric and non-numeric values to demonstrate how it handles different cases.
Output:
"Is 7 is odd?" true "Is 20 is odd?" false "Is -5 is odd?" true "Is ABC is odd?" false
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript interface, type, and union types.
Next: Extracting Numbers, Booleans, and Strings from a Mixed TypeScript Array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/typescript-exercises/typescript-advance-types-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics