IsOdd
Less than 1 minuteTC-Medium
IsOdd
Problem
Return true if a number is odd, false otherwise.
type T0 = IsOdd<1> // true
type T1 = IsOdd<2> // false
type T2 = IsOdd<1001> // true
type T3 = IsOdd<-99> // trueSolution
type IsOdd<N extends number> =
`${N}` extends `${string}${'1' | '3' | '5' | '7' | '9'}`
? true
: falseHow it works:
- Convert
Nto its string representation using a template literal. - Check whether the last digit is one of
1,3,5,7,9using a template literal union. - If yes, the number is odd — return
true. - Otherwise return
false.
This works for negative numbers too because -99 ends in 9.
Key Takeaways
- Checking the last digit of a number's string representation is far simpler than tuple-based parity checks.
- Template literal unions (
'1' | '3' | '5' | '7' | '9') let you match any of several suffixes in one expression. - This approach handles arbitrarily large numbers without hitting recursion depth limits.
