Skip to content

fix: support const enums from adjacent .d.ts files - #833

Open
mrpmohiburrahman wants to merge 1 commit into
privatenumber:masterfrom
mrpmohiburrahman:fix/adjacent-dts-const-enum
Open

mrpmohiburrahman wants to merge 1 commit into
privatenumber:masterfrom
mrpmohiburrahman:fix/adjacent-dts-const-enum

Conversation

@mrpmohiburrahman

Copy link
Copy Markdown

Problem

tsc inlines const enum members at compile time, so the emitted .js never exports them. tsx transforms one file at a time and does not read .d.ts, so the identifier reaches runtime.

With some-lib/index.d.ts declaring:

export declare const enum TestEnum { Foo = 'foo' }

a named import fails:

SyntaxError: The requested module './some-lib/index.js' does not provide an export named 'TestEnum'

A namespace import yields undefined instead of throwing.

Changes

When an ESM .js has an adjacent .d.ts, its exported const enums are run through esbuild and appended to the module source. Fixing the imported side covers named, namespace and default imports at once.

  • Cached per path, misses included, behind an existsSync guard.
  • Bails when the module already exports the name, so a real export wins.
  • Emitted under a generated local, exported as an alias, so a same-named local is not redeclared.
  • Appended rather than prepended, so existing lines keep their source-map positions.

Scoped to the adjacent .d.ts, per your comment on #321. Still unsupported: typeRoots, global ambient declarations, require() through the CommonJS loader, declare const enum X {} paired with a separate export { X }, and .mjs beside a .d.ts rather than .d.mts.

One divergence from tsc: it erases the enum, this materialises it, so the name appears in Object.keys(namespace).

10 tests added, each confirmed failing before the change. Suite 187 → 197 passing, with the same 3 pre-existing failures. Lint and type-check clean.

Fixes #321

tsc inlines const enum members into each consumer at compile time, so the
emitted .js never exports them. tsx transforms one file at a time and does
not read .d.ts, so the identifier reaches runtime and fails there.

Read the .d.ts beside a .js module, extract its exported const enums with
esbuild, and append them to the module source. Fixing the imported side
covers every import form at once.

Fixes privatenumber#321

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cannot access ambient const enums when run by tsx but no problem by ts-node

1 participant