Typescript Odd Number Type

Most people: No, you cannot create an odd number type with Typescript

Meanwhile me:

type OddNumber<
X extends number,
Y extends unknown[] = [1],
Z extends number = never
> = Y[‘length’] extends X
? Z | Y[‘length’]
: OddNumber<X, [1, 1, …Y], Z | Y[‘length’]>
type a = OddNumber<1> // 1
type b = OddNumber< 3 > // 1 | 3
type c = OddNumber<5> // 1 | 3 | 5
type d = OddNumber<7> // 1 | 3 | 5 | 7

playground

with some limitations, the input must an odd number, and cannot exceed 1999 (maximum depth of typescript recursion is only 1000)

you can do even number type using similar logic

--

--

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Acid Coder

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)