How does `moduleResolution` impact the type-correctness of enum comparisons?

17 Views Asked by At

I have a codebase that contains a union of types; each type has a type property that is the value of a string enum.

enum Foo {
  Alpha: 'Alpha',
  Beta: 'Beta',
  // ... 27 other values
}

type Alpha {
  "type": Foo.Alpha,
  // ... stuff
}

type Beta {
  "type": Foo.Beta;
  // ... stuff
}

type Baz = Aplha | Beta // | ... etc

In a different module within the codebase, I have a function:

const operateOnBaz = (baz: Baz) => {
  switch (baz.type) {
    case Foo.Alpha: //do stuff with Alpha
    case Foo.Beta: //do stuff with Beta
    // etc
  }
}

This was all working fine: no tsc errors, no eslint errors.

When I changed the moduleResolution from NodeNext to Bundler in the relevant tsconfig.json file, two things happened:

  1. ESLint reports The case statement does not have a shared enum type with the switch predicate on each case statement
  2. TypeScript no longer discriminates the union within the case statements, leading to type errors.

I have tried switching to if/elses, but it's the same problem.

What I expected was that this code would not be dependent on the value of moduleResolution.

I know that I could switch from an enum to plain strings or something similar, but that's a lot of rework to do in lieu of actually understanding what is going on.

I'm looking to migrate from Node to Bun because of issues with how NodeJS handles named imports from CJS modules. Not doing that would also be an option.

Ultimately, I'm trying to understand how moduleResolution changes the behavior of enums and discriminated unions.

0

There are 0 best solutions below