0

TypeScript has enum flags. Example:

enum Traits {
    None = 0,
    Friendly = 1 << 0, // 0001 -- the bitshift is unnecessary, but done for consistency
    Mean = 1 << 1,     // 0010
    Funny = 1 << 2,    // 0100
    Boring = 1 << 3,   // 1000
    All = ~(~0 << 4)   // 1111
}

What is the maximum number you can have in a single enum?

I assume it is either 32 because of 32 bit integers, or something like 53 due to MAX_SAFE_INTEGER.

Which is it? Or is it something else entirely?

If it is indeed more than 32, I assume you will have to generate the numbers using something other than the bit-shifting operator, since I believe that may only work with numbers up to 32 bit?

Ryan Peschel
  • 11,087
  • 19
  • 74
  • 136

1 Answers1

0

The max is a shift of 31 so 32 values

enum Test {
    Ok = 1 << 31, // -2147483648
    Max = ~(~0 << 31), // 2147483647
    Overflow = 1 << 32 // 1
}

Edit:
Using directly number you can get up to 53 bits :

Number.MAX_SAFE_INTEGER.toString(2) // '11111111111111111111111111111111111111111111111111111'

Obove MAX_SAFE_INTEGER you're hitting the limit :

(Number.MAX_SAFE_INTEGER + 2).toString(2) === (Number.MAX_SAFE_INTEGER + 1).toString(2) // true

Also you can note:

enum Test {
    test = Number.MAX_SAFE_INTEGER,
    test2 = Number.MAX_SAFE_INTEGER + 1, 
    test3 = Number.MAX_SAFE_INTEGER + 2, 
}

console.log(Test.test1 === Test.test3) // error
console.log(Test.test2 === Test.test3); // true 

Playground

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
  • Yeah but you don't have to shift, no? What happens if you generate, say, `1 << 35` via other means? I can just google that that value is `68719476736`. – Ryan Peschel Dec 22 '22 at 14:54