'Only odd numbers type for Typescript
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 1:[1]
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<3> // 1 | 3
type b = OddNumber<5> // 1 | 3 | 5
type c = OddNumber<7> // 1 | 3 | 5 | 7
with some limitations, the input must be at least 3, must be an odd number, and cannot exceed 1999 (maximum depth of typescript recursion is only 1000)
Solution 2:[2]
Maybe creating a new class can be helpful on this case?
class OddNumber {
value: number;
constructor(value: number) {
if (value % 2 != 0)
throw new Error("Even number is not assignable to type 'OddNumber'.");
this.value = value;
}
};
let oddNumber = new OddNumber(4);
console.log(oddNumber.value); // It will log 4
let evenNumber = new OddNumber(5); // It will throw an exception here
console.log(evenNumber.value);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Patrick Freitas |
