Yuzhe's Blog

yuzhes

IsOdd

IsOdd

Problem Link

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>   // true

Solution

type IsOdd<N extends number> =
  `${N}` extends `${string}${'1' | '3' | '5' | '7' | '9'}`
    ? true
    : false

How it works:

  1. Convert N to its string representation using a template literal.
  2. Check whether the last digit is one of 1, 3, 5, 7, 9 using a template literal union.
  3. If yes, the number is odd — return true.
  4. Otherwise return false.

This works for negative numbers too because -99 ends in 9.

Key Takeaways