Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consume enum from ambient TypeScript module using @babel/preset-typescript?

Is it possible to consume an enum from a file being transpiled by babel using @babel/preset-typescript?

mymodule.d.ts

declare module 'mymodule' {
  export enum Fruit {
    apple = 'Apple',
  }
}

script.js

import { Fruit } from 'mymodule'

assert.equals(Fruit.apple === 'Apple')

Fruit will be undefined in this case since babel does not know about the ambient declaration.

Is there a way to get around this besides declaring a separate enum/constants file and directly importing those in both places (the ambient module and the script)?

like image 240
Adam Thompson Avatar asked Jun 07 '26 09:06

Adam Thompson


1 Answers

You cannot import executable code from a declaration file (*.d.ts).

You can use a declaration file to describe what's happening in another module. In this case, if Fruit exists in mymodule you could declare its shape in mymodule.d.ts — but it's not the declaration that's executed, but the actual code living in mymodule.

In other words, Fruit must exist in a *.ts or *.js file in order to be used in runtime.

like image 166
Karol Majewski Avatar answered Jun 10 '26 18:06

Karol Majewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!