return true is a number is odd Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement an IsOdd<T> type that determines whether a given number type is an odd integer, returning true for odd integers and false otherwise.
return true is a number is odd
Change the following code to make the test cases pass (no type check errors).
type IsOdd<T extends number> =
number extends T
? false
: `${T}` extends `${string}${'1' | '3' | '5' | '7' | '9'}`
? true
: false;How it works:
number extends T handles the wide number type. If T is not a specific numeric literal, we cannot determine oddness, so we return false.\${T}``.'1', '3', '5', '7', '9') using the pattern \${string}${'1' | '3' | '5' | '7' | '9'}``.2023 (ends in '3', so odd) and 1926 (ends in '6', so even).2.3 have their string representation as "2.3", which ends in '3' -- but this is not a problem because the last character check only matters for integer-looking strings. Actually, "2.3" does end in '3', so we need the scientific notation edge case: 3e23 becomes "3e+23" which ends in '3' but should be false. However, looking at the test cases, 3e23 returns false because "3e+23" ends in '3'... Let me reconsider.A more robust solution that also rejects non-integers:
type IsOdd<T extends number> =
number extends T
? false
: `${T}` extends `${bigint}`
? `${T}` extends `${string}${'1' | '3' | '5' | '7' | '9'}`
? true
: false
: false;How this improved version works:
number type, we first verify T is an integer by checking if its string representation matches \${bigint}`. This rejects decimals like 2.3and scientific notation like3e+23`.2.3 converts to "2.3" which does not match bigint, so it returns false.3e23 converts to "3e+23" which does not match bigint, so it returns false.5 converts to "5" which matches bigint and ends in '5', so it returns true.This challenge helps you understand template literal types for numeric string analysis and how to apply these patterns in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount