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
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
Top comments (4)
Ok, challenge accepted. If you are not affraid of generic programming you can do Odd or Even type check without limitation :
check on playground
good solution, I further simplified your code
however there is fundamental different between your solution and my original solution
yours can only be used in function, the original solution is intended to assign to a variable, for example
which is why it is a odd number type, not odd number check
I do however agree that the function one is more versatile
An odd methodπ
This type contains more logic than my first customer project.
I draw my π© before that