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.
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)
playground
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With