admin管理员组

文章数量:1401459

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.

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.

Share Improve this question edited Jun 18, 2021 at 17:08 Robert Hovhannisyan asked Jun 18, 2021 at 16:55 Robert HovhannisyanRobert Hovhannisyan 3,3706 gold badges24 silver badges51 bronze badges 10
  • Can you provide more information, like the code you may be trying to write it as? That may help us understand the problem better. – Daveguy Commented Jun 18, 2021 at 17:04
  • @RobertHovhannisyan generally x % 2 == 1 is the way to determine whether a number variable is odd. – Daveguy Commented Jun 18, 2021 at 17:05
  • 2 @Daveguy OP is attempting to make a type to enforce a number's oddness. – Dave Newton Commented Jun 18, 2021 at 17:06
  • 2 @Daveguy A type, as in const foo: oddInteger or whatever. – Dave Newton Commented Jun 18, 2021 at 17:09
  • 2 I don't think this is possible in TypeScript (or most type systems, even). – Bergi Commented Jun 18, 2021 at 17:14
 |  Show 5 more ments

2 Answers 2

Reset to default 8

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);

本文标签: javascriptOnly odd numbers type for TypescriptStack Overflow