Issue
I want to have a type that checks if the value is an odd number or not. I tried to find something but I find only hardcoded solutions like odds: 1 | 3 | 5 | 7 | 9
. But I want to know is there a dynamic way to do it only with Typescript.
I know that for example in JS we can find out that the number is odd or not with this expression x % 2 === 1
. I want to know is there a way to define a type with an expression like this.
Solution
Yes, it is possible
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, input must be an odd number and cannot exceed 1999 (maximum depth of typescript recursion is only 1000)
Answered By - Acid Coder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.