#30301Medium

IsOdd

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.

Challenge Instructions: IsOdd

Medium

return true is a number is odd

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type cases = [
  Expect<Equal<IsOdd<5>, true>>,
  Expect<Equal<IsOdd<2023>, true>>,
  Expect<Equal<IsOdd<1453>, true>>,
  Expect<Equal<IsOdd<1926>, false>>,
  Expect<Equal<IsOdd<2.3>, false>>,
  Expect<Equal<IsOdd<3e23>, false>>,
  Expect<Equal<IsOdd<3>, true>>,
  Expect<Equal<IsOdd<number>, false>>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

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

How it works:

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:

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.

Share this challenge